1//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr constant evaluator.
10//
11// Constant expression evaluation produces four main results:
12//
13// * A success/failure flag indicating whether constant folding was successful.
14// This is the 'bool' return value used by most of the code in this file. A
15// 'false' return value indicates that constant folding has failed, and any
16// appropriate diagnostic has already been produced.
17//
18// * An evaluated result, valid only if constant folding has not failed.
19//
20// * A flag indicating if evaluation encountered (unevaluated) side-effects.
21// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22// where it is possible to determine the evaluated result regardless.
23//
24// * A set of notes indicating why the evaluation was not a constant expression
25// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26// too, why the expression could not be folded.
27//
28// If we are checking for a potential constant expression, failure to constant
29// fold a potential constant sub-expression will be indicated by a 'false'
30// return value (the expression could not be folded) and no diagnostic (the
31// expression is not necessarily non-constant).
32//
33//===----------------------------------------------------------------------===//
34
35#include "clang/AST/APValue.h"
36#include "clang/AST/ASTContext.h"
37#include "clang/AST/ASTDiagnostic.h"
38#include "clang/AST/ASTLambda.h"
39#include "clang/AST/CharUnits.h"
40#include "clang/AST/CurrentSourceLocExprScope.h"
41#include "clang/AST/CXXInheritance.h"
42#include "clang/AST/Expr.h"
43#include "clang/AST/OSLog.h"
44#include "clang/AST/RecordLayout.h"
45#include "clang/AST/StmtVisitor.h"
46#include "clang/AST/TypeLoc.h"
47#include "clang/Basic/Builtins.h"
48#include "clang/Basic/FixedPoint.h"
49#include "clang/Basic/TargetInfo.h"
50#include "llvm/Support/SaveAndRestore.h"
51#include "llvm/Support/raw_ostream.h"
52#include <cstring>
53#include <functional>
54
55#define DEBUG_TYPE "exprconstant"
56
57using namespace clang;
58using llvm::APSInt;
59using llvm::APFloat;
60
61static bool IsGlobalLValue(APValue::LValueBase B);
62
63namespace {
64 struct LValue;
65 struct CallStackFrame;
66 struct EvalInfo;
67
68 using SourceLocExprScopeGuard =
69 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
70
71 static QualType getType(APValue::LValueBase B) {
72 if (!B) return QualType();
73 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
74 // FIXME: It's unclear where we're supposed to take the type from, and
75 // this actually matters for arrays of unknown bound. Eg:
76 //
77 // extern int arr[]; void f() { extern int arr[3]; };
78 // constexpr int *p = &arr[1]; // valid?
79 //
80 // For now, we take the array bound from the most recent declaration.
81 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
82 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
83 QualType T = Redecl->getType();
84 if (!T->isIncompleteArrayType())
85 return T;
86 }
87 return D->getType();
88 }
89
90 if (B.is<TypeInfoLValue>())
91 return B.getTypeInfoType();
92
93 const Expr *Base = B.get<const Expr*>();
94
95 // For a materialized temporary, the type of the temporary we materialized
96 // may not be the type of the expression.
97 if (const MaterializeTemporaryExpr *MTE =
98 dyn_cast<MaterializeTemporaryExpr>(Base)) {
99 SmallVector<const Expr *, 2> CommaLHSs;
100 SmallVector<SubobjectAdjustment, 2> Adjustments;
101 const Expr *Temp = MTE->GetTemporaryExpr();
102 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
103 Adjustments);
104 // Keep any cv-qualifiers from the reference if we generated a temporary
105 // for it directly. Otherwise use the type after adjustment.
106 if (!Adjustments.empty())
107 return Inner->getType();
108 }
109
110 return Base->getType();
111 }
112
113 /// Get an LValue path entry, which is known to not be an array index, as a
114 /// field declaration.
115 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
116 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
117 }
118 /// Get an LValue path entry, which is known to not be an array index, as a
119 /// base class declaration.
120 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
121 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
122 }
123 /// Determine whether this LValue path entry for a base class names a virtual
124 /// base class.
125 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
126 return E.getAsBaseOrMember().getInt();
127 }
128
129 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
130 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
131 if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
132 return DirectCallee->getAttr<AllocSizeAttr>();
133 if (const Decl *IndirectCallee = CE->getCalleeDecl())
134 return IndirectCallee->getAttr<AllocSizeAttr>();
135 return nullptr;
136 }
137
138 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
139 /// This will look through a single cast.
140 ///
141 /// Returns null if we couldn't unwrap a function with alloc_size.
142 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
143 if (!E->getType()->isPointerType())
144 return nullptr;
145
146 E = E->IgnoreParens();
147 // If we're doing a variable assignment from e.g. malloc(N), there will
148 // probably be a cast of some kind. In exotic cases, we might also see a
149 // top-level ExprWithCleanups. Ignore them either way.
150 if (const auto *FE = dyn_cast<FullExpr>(E))
151 E = FE->getSubExpr()->IgnoreParens();
152
153 if (const auto *Cast = dyn_cast<CastExpr>(E))
154 E = Cast->getSubExpr()->IgnoreParens();
155
156 if (const auto *CE = dyn_cast<CallExpr>(E))
157 return getAllocSizeAttr(CE) ? CE : nullptr;
158 return nullptr;
159 }
160
161 /// Determines whether or not the given Base contains a call to a function
162 /// with the alloc_size attribute.
163 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
164 const auto *E = Base.dyn_cast<const Expr *>();
165 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
166 }
167
168 /// The bound to claim that an array of unknown bound has.
169 /// The value in MostDerivedArraySize is undefined in this case. So, set it
170 /// to an arbitrary value that's likely to loudly break things if it's used.
171 static const uint64_t AssumedSizeForUnsizedArray =
172 std::numeric_limits<uint64_t>::max() / 2;
173
174 /// Determines if an LValue with the given LValueBase will have an unsized
175 /// array in its designator.
176 /// Find the path length and type of the most-derived subobject in the given
177 /// path, and find the size of the containing array, if any.
178 static unsigned
179 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
180 ArrayRef<APValue::LValuePathEntry> Path,
181 uint64_t &ArraySize, QualType &Type, bool &IsArray,
182 bool &FirstEntryIsUnsizedArray) {
183 // This only accepts LValueBases from APValues, and APValues don't support
184 // arrays that lack size info.
185 assert(!isBaseAnAllocSizeCall(Base) &&
186 "Unsized arrays shouldn't appear here");
187 unsigned MostDerivedLength = 0;
188 Type = getType(Base);
189
190 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
191 if (Type->isArrayType()) {
192 const ArrayType *AT = Ctx.getAsArrayType(Type);
193 Type = AT->getElementType();
194 MostDerivedLength = I + 1;
195 IsArray = true;
196
197 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
198 ArraySize = CAT->getSize().getZExtValue();
199 } else {
200 assert(I == 0 && "unexpected unsized array designator");
201 FirstEntryIsUnsizedArray = true;
202 ArraySize = AssumedSizeForUnsizedArray;
203 }
204 } else if (Type->isAnyComplexType()) {
205 const ComplexType *CT = Type->castAs<ComplexType>();
206 Type = CT->getElementType();
207 ArraySize = 2;
208 MostDerivedLength = I + 1;
209 IsArray = true;
210 } else if (const FieldDecl *FD = getAsField(Path[I])) {
211 Type = FD->getType();
212 ArraySize = 0;
213 MostDerivedLength = I + 1;
214 IsArray = false;
215 } else {
216 // Path[I] describes a base class.
217 ArraySize = 0;
218 IsArray = false;
219 }
220 }
221 return MostDerivedLength;
222 }
223
224 // The order of this enum is important for diagnostics.
225 enum CheckSubobjectKind {
226 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
227 CSK_Real, CSK_Imag
228 };
229
230 /// A path from a glvalue to a subobject of that glvalue.
231 struct SubobjectDesignator {
232 /// True if the subobject was named in a manner not supported by C++11. Such
233 /// lvalues can still be folded, but they are not core constant expressions
234 /// and we cannot perform lvalue-to-rvalue conversions on them.
235 unsigned Invalid : 1;
236
237 /// Is this a pointer one past the end of an object?
238 unsigned IsOnePastTheEnd : 1;
239
240 /// Indicator of whether the first entry is an unsized array.
241 unsigned FirstEntryIsAnUnsizedArray : 1;
242
243 /// Indicator of whether the most-derived object is an array element.
244 unsigned MostDerivedIsArrayElement : 1;
245
246 /// The length of the path to the most-derived object of which this is a
247 /// subobject.
248 unsigned MostDerivedPathLength : 28;
249
250 /// The size of the array of which the most-derived object is an element.
251 /// This will always be 0 if the most-derived object is not an array
252 /// element. 0 is not an indicator of whether or not the most-derived object
253 /// is an array, however, because 0-length arrays are allowed.
254 ///
255 /// If the current array is an unsized array, the value of this is
256 /// undefined.
257 uint64_t MostDerivedArraySize;
258
259 /// The type of the most derived object referred to by this address.
260 QualType MostDerivedType;
261
262 typedef APValue::LValuePathEntry PathEntry;
263
264 /// The entries on the path from the glvalue to the designated subobject.
265 SmallVector<PathEntry, 8> Entries;
266
267 SubobjectDesignator() : Invalid(true) {}
268
269 explicit SubobjectDesignator(QualType T)
270 : Invalid(false), IsOnePastTheEnd(false),
271 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
272 MostDerivedPathLength(0), MostDerivedArraySize(0),
273 MostDerivedType(T) {}
274
275 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
276 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
277 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
278 MostDerivedPathLength(0), MostDerivedArraySize(0) {
279 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
280 if (!Invalid) {
281 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
282 ArrayRef<PathEntry> VEntries = V.getLValuePath();
283 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
284 if (V.getLValueBase()) {
285 bool IsArray = false;
286 bool FirstIsUnsizedArray = false;
287 MostDerivedPathLength = findMostDerivedSubobject(
288 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
289 MostDerivedType, IsArray, FirstIsUnsizedArray);
290 MostDerivedIsArrayElement = IsArray;
291 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
292 }
293 }
294 }
295
296 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
297 unsigned NewLength) {
298 if (Invalid)
299 return;
300
301 assert(Base && "cannot truncate path for null pointer");
302 assert(NewLength <= Entries.size() && "not a truncation");
303
304 if (NewLength == Entries.size())
305 return;
306 Entries.resize(NewLength);
307
308 bool IsArray = false;
309 bool FirstIsUnsizedArray = false;
310 MostDerivedPathLength = findMostDerivedSubobject(
311 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
312 FirstIsUnsizedArray);
313 MostDerivedIsArrayElement = IsArray;
314 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
315 }
316
317 void setInvalid() {
318 Invalid = true;
319 Entries.clear();
320 }
321
322 /// Determine whether the most derived subobject is an array without a
323 /// known bound.
324 bool isMostDerivedAnUnsizedArray() const {
325 assert(!Invalid && "Calling this makes no sense on invalid designators");
326 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
327 }
328
329 /// Determine what the most derived array's size is. Results in an assertion
330 /// failure if the most derived array lacks a size.
331 uint64_t getMostDerivedArraySize() const {
332 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
333 return MostDerivedArraySize;
334 }
335
336 /// Determine whether this is a one-past-the-end pointer.
337 bool isOnePastTheEnd() const {
338 assert(!Invalid);
339 if (IsOnePastTheEnd)
340 return true;
341 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
342 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
343 MostDerivedArraySize)
344 return true;
345 return false;
346 }
347
348 /// Get the range of valid index adjustments in the form
349 /// {maximum value that can be subtracted from this pointer,
350 /// maximum value that can be added to this pointer}
351 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
352 if (Invalid || isMostDerivedAnUnsizedArray())
353 return {0, 0};
354
355 // [expr.add]p4: For the purposes of these operators, a pointer to a
356 // nonarray object behaves the same as a pointer to the first element of
357 // an array of length one with the type of the object as its element type.
358 bool IsArray = MostDerivedPathLength == Entries.size() &&
359 MostDerivedIsArrayElement;
360 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
361 : (uint64_t)IsOnePastTheEnd;
362 uint64_t ArraySize =
363 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
364 return {ArrayIndex, ArraySize - ArrayIndex};
365 }
366
367 /// Check that this refers to a valid subobject.
368 bool isValidSubobject() const {
369 if (Invalid)
370 return false;
371 return !isOnePastTheEnd();
372 }
373 /// Check that this refers to a valid subobject, and if not, produce a
374 /// relevant diagnostic and set the designator as invalid.
375 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
376
377 /// Get the type of the designated object.
378 QualType getType(ASTContext &Ctx) const {
379 assert(!Invalid && "invalid designator has no subobject type");
380 return MostDerivedPathLength == Entries.size()
381 ? MostDerivedType
382 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
383 }
384
385 /// Update this designator to refer to the first element within this array.
386 void addArrayUnchecked(const ConstantArrayType *CAT) {
387 Entries.push_back(PathEntry::ArrayIndex(0));
388
389 // This is a most-derived object.
390 MostDerivedType = CAT->getElementType();
391 MostDerivedIsArrayElement = true;
392 MostDerivedArraySize = CAT->getSize().getZExtValue();
393 MostDerivedPathLength = Entries.size();
394 }
395 /// Update this designator to refer to the first element within the array of
396 /// elements of type T. This is an array of unknown size.
397 void addUnsizedArrayUnchecked(QualType ElemTy) {
398 Entries.push_back(PathEntry::ArrayIndex(0));
399
400 MostDerivedType = ElemTy;
401 MostDerivedIsArrayElement = true;
402 // The value in MostDerivedArraySize is undefined in this case. So, set it
403 // to an arbitrary value that's likely to loudly break things if it's
404 // used.
405 MostDerivedArraySize = AssumedSizeForUnsizedArray;
406 MostDerivedPathLength = Entries.size();
407 }
408 /// Update this designator to refer to the given base or member of this
409 /// object.
410 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
411 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
412
413 // If this isn't a base class, it's a new most-derived object.
414 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
415 MostDerivedType = FD->getType();
416 MostDerivedIsArrayElement = false;
417 MostDerivedArraySize = 0;
418 MostDerivedPathLength = Entries.size();
419 }
420 }
421 /// Update this designator to refer to the given complex component.
422 void addComplexUnchecked(QualType EltTy, bool Imag) {
423 Entries.push_back(PathEntry::ArrayIndex(Imag));
424
425 // This is technically a most-derived object, though in practice this
426 // is unlikely to matter.
427 MostDerivedType = EltTy;
428 MostDerivedIsArrayElement = true;
429 MostDerivedArraySize = 2;
430 MostDerivedPathLength = Entries.size();
431 }
432 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
433 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
434 const APSInt &N);
435 /// Add N to the address of this subobject.
436 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
437 if (Invalid || !N) return;
438 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
439 if (isMostDerivedAnUnsizedArray()) {
440 diagnoseUnsizedArrayPointerArithmetic(Info, E);
441 // Can't verify -- trust that the user is doing the right thing (or if
442 // not, trust that the caller will catch the bad behavior).
443 // FIXME: Should we reject if this overflows, at least?
444 Entries.back() = PathEntry::ArrayIndex(
445 Entries.back().getAsArrayIndex() + TruncatedN);
446 return;
447 }
448
449 // [expr.add]p4: For the purposes of these operators, a pointer to a
450 // nonarray object behaves the same as a pointer to the first element of
451 // an array of length one with the type of the object as its element type.
452 bool IsArray = MostDerivedPathLength == Entries.size() &&
453 MostDerivedIsArrayElement;
454 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
455 : (uint64_t)IsOnePastTheEnd;
456 uint64_t ArraySize =
457 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
458
459 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
460 // Calculate the actual index in a wide enough type, so we can include
461 // it in the note.
462 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
463 (llvm::APInt&)N += ArrayIndex;
464 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
465 diagnosePointerArithmetic(Info, E, N);
466 setInvalid();
467 return;
468 }
469
470 ArrayIndex += TruncatedN;
471 assert(ArrayIndex <= ArraySize &&
472 "bounds check succeeded for out-of-bounds index");
473
474 if (IsArray)
475 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
476 else
477 IsOnePastTheEnd = (ArrayIndex != 0);
478 }
479 };
480
481 /// A stack frame in the constexpr call stack.
482 struct CallStackFrame {
483 EvalInfo &Info;
484
485 /// Parent - The caller of this stack frame.
486 CallStackFrame *Caller;
487
488 /// Callee - The function which was called.
489 const FunctionDecl *Callee;
490
491 /// This - The binding for the this pointer in this call, if any.
492 const LValue *This;
493
494 /// Arguments - Parameter bindings for this function call, indexed by
495 /// parameters' function scope indices.
496 APValue *Arguments;
497
498 /// Source location information about the default argument or default
499 /// initializer expression we're evaluating, if any.
500 CurrentSourceLocExprScope CurSourceLocExprScope;
501
502 // Note that we intentionally use std::map here so that references to
503 // values are stable.
504 typedef std::pair<const void *, unsigned> MapKeyTy;
505 typedef std::map<MapKeyTy, APValue> MapTy;
506 /// Temporaries - Temporary lvalues materialized within this stack frame.
507 MapTy Temporaries;
508
509 /// CallLoc - The location of the call expression for this call.
510 SourceLocation CallLoc;
511
512 /// Index - The call index of this call.
513 unsigned Index;
514
515 /// The stack of integers for tracking version numbers for temporaries.
516 SmallVector<unsigned, 2> TempVersionStack = {1};
517 unsigned CurTempVersion = TempVersionStack.back();
518
519 unsigned getTempVersion() const { return TempVersionStack.back(); }
520
521 void pushTempVersion() {
522 TempVersionStack.push_back(++CurTempVersion);
523 }
524
525 void popTempVersion() {
526 TempVersionStack.pop_back();
527 }
528
529 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
530 // on the overall stack usage of deeply-recursing constexpr evaluations.
531 // (We should cache this map rather than recomputing it repeatedly.)
532 // But let's try this and see how it goes; we can look into caching the map
533 // as a later change.
534
535 /// LambdaCaptureFields - Mapping from captured variables/this to
536 /// corresponding data members in the closure class.
537 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
538 FieldDecl *LambdaThisCaptureField;
539
540 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
541 const FunctionDecl *Callee, const LValue *This,
542 APValue *Arguments);
543 ~CallStackFrame();
544
545 // Return the temporary for Key whose version number is Version.
546 APValue *getTemporary(const void *Key, unsigned Version) {
547 MapKeyTy KV(Key, Version);
548 auto LB = Temporaries.lower_bound(KV);
549 if (LB != Temporaries.end() && LB->first == KV)
550 return &LB->second;
551 // Pair (Key,Version) wasn't found in the map. Check that no elements
552 // in the map have 'Key' as their key.
553 assert((LB == Temporaries.end() || LB->first.first != Key) &&
554 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
555 "Element with key 'Key' found in map");
556 return nullptr;
557 }
558
559 // Return the current temporary for Key in the map.
560 APValue *getCurrentTemporary(const void *Key) {
561 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
562 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
563 return &std::prev(UB)->second;
564 return nullptr;
565 }
566
567 // Return the version number of the current temporary for Key.
568 unsigned getCurrentTemporaryVersion(const void *Key) const {
569 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
570 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
571 return std::prev(UB)->first.second;
572 return 0;
573 }
574
575 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
576 };
577
578 /// Temporarily override 'this'.
579 class ThisOverrideRAII {
580 public:
581 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
582 : Frame(Frame), OldThis(Frame.This) {
583 if (Enable)
584 Frame.This = NewThis;
585 }
586 ~ThisOverrideRAII() {
587 Frame.This = OldThis;
588 }
589 private:
590 CallStackFrame &Frame;
591 const LValue *OldThis;
592 };
593
594 /// A partial diagnostic which we might know in advance that we are not going
595 /// to emit.
596 class OptionalDiagnostic {
597 PartialDiagnostic *Diag;
598
599 public:
600 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
601 : Diag(Diag) {}
602
603 template<typename T>
604 OptionalDiagnostic &operator<<(const T &v) {
605 if (Diag)
606 *Diag << v;
607 return *this;
608 }
609
610 OptionalDiagnostic &operator<<(const APSInt &I) {
611 if (Diag) {
612 SmallVector<char, 32> Buffer;
613 I.toString(Buffer);
614 *Diag << StringRef(Buffer.data(), Buffer.size());
615 }
616 return *this;
617 }
618
619 OptionalDiagnostic &operator<<(const APFloat &F) {
620 if (Diag) {
621 // FIXME: Force the precision of the source value down so we don't
622 // print digits which are usually useless (we don't really care here if
623 // we truncate a digit by accident in edge cases). Ideally,
624 // APFloat::toString would automatically print the shortest
625 // representation which rounds to the correct value, but it's a bit
626 // tricky to implement.
627 unsigned precision =
628 llvm::APFloat::semanticsPrecision(F.getSemantics());
629 precision = (precision * 59 + 195) / 196;
630 SmallVector<char, 32> Buffer;
631 F.toString(Buffer, precision);
632 *Diag << StringRef(Buffer.data(), Buffer.size());
633 }
634 return *this;
635 }
636
637 OptionalDiagnostic &operator<<(const APFixedPoint &FX) {
638 if (Diag) {
639 SmallVector<char, 32> Buffer;
640 FX.toString(Buffer);
641 *Diag << StringRef(Buffer.data(), Buffer.size());
642 }
643 return *this;
644 }
645 };
646
647 /// A cleanup, and a flag indicating whether it is lifetime-extended.
648 class Cleanup {
649 llvm::PointerIntPair<APValue*, 1, bool> Value;
650
651 public:
652 Cleanup(APValue *Val, bool IsLifetimeExtended)
653 : Value(Val, IsLifetimeExtended) {}
654
655 bool isLifetimeExtended() const { return Value.getInt(); }
656 void endLifetime() {
657 *Value.getPointer() = APValue();
658 }
659 };
660
661 /// A reference to an object whose construction we are currently evaluating.
662 struct ObjectUnderConstruction {
663 APValue::LValueBase Base;
664 ArrayRef<APValue::LValuePathEntry> Path;
665 friend bool operator==(const ObjectUnderConstruction &LHS,
666 const ObjectUnderConstruction &RHS) {
667 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
668 }
669 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
670 return llvm::hash_combine(Obj.Base, Obj.Path);
671 }
672 };
673 enum class ConstructionPhase { None, Bases, AfterBases };
674}
675
676namespace llvm {
677template<> struct DenseMapInfo<ObjectUnderConstruction> {
678 using Base = DenseMapInfo<APValue::LValueBase>;
679 static ObjectUnderConstruction getEmptyKey() {
680 return {Base::getEmptyKey(), {}}; }
681 static ObjectUnderConstruction getTombstoneKey() {
682 return {Base::getTombstoneKey(), {}};
683 }
684 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
685 return hash_value(Object);
686 }
687 static bool isEqual(const ObjectUnderConstruction &LHS,
688 const ObjectUnderConstruction &RHS) {
689 return LHS == RHS;
690 }
691};
692}
693
694namespace {
695 /// EvalInfo - This is a private struct used by the evaluator to capture
696 /// information about a subexpression as it is folded. It retains information
697 /// about the AST context, but also maintains information about the folded
698 /// expression.
699 ///
700 /// If an expression could be evaluated, it is still possible it is not a C
701 /// "integer constant expression" or constant expression. If not, this struct
702 /// captures information about how and why not.
703 ///
704 /// One bit of information passed *into* the request for constant folding
705 /// indicates whether the subexpression is "evaluated" or not according to C
706 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
707 /// evaluate the expression regardless of what the RHS is, but C only allows
708 /// certain things in certain situations.
709 struct EvalInfo {
710 ASTContext &Ctx;
711
712 /// EvalStatus - Contains information about the evaluation.
713 Expr::EvalStatus &EvalStatus;
714
715 /// CurrentCall - The top of the constexpr call stack.
716 CallStackFrame *CurrentCall;
717
718 /// CallStackDepth - The number of calls in the call stack right now.
719 unsigned CallStackDepth;
720
721 /// NextCallIndex - The next call index to assign.
722 unsigned NextCallIndex;
723
724 /// StepsLeft - The remaining number of evaluation steps we're permitted
725 /// to perform. This is essentially a limit for the number of statements
726 /// we will evaluate.
727 unsigned StepsLeft;
728
729 /// BottomFrame - The frame in which evaluation started. This must be
730 /// initialized after CurrentCall and CallStackDepth.
731 CallStackFrame BottomFrame;
732
733 /// A stack of values whose lifetimes end at the end of some surrounding
734 /// evaluation frame.
735 llvm::SmallVector<Cleanup, 16> CleanupStack;
736
737 /// EvaluatingDecl - This is the declaration whose initializer is being
738 /// evaluated, if any.
739 APValue::LValueBase EvaluatingDecl;
740
741 /// EvaluatingDeclValue - This is the value being constructed for the
742 /// declaration whose initializer is being evaluated, if any.
743 APValue *EvaluatingDeclValue;
744
745 /// Set of objects that are currently being constructed.
746 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
747 ObjectsUnderConstruction;
748
749 struct EvaluatingConstructorRAII {
750 EvalInfo &EI;
751 ObjectUnderConstruction Object;
752 bool DidInsert;
753 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
754 bool HasBases)
755 : EI(EI), Object(Object) {
756 DidInsert =
757 EI.ObjectsUnderConstruction
758 .insert({Object, HasBases ? ConstructionPhase::Bases
759 : ConstructionPhase::AfterBases})
760 .second;
761 }
762 void finishedConstructingBases() {
763 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
764 }
765 ~EvaluatingConstructorRAII() {
766 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
767 }
768 };
769
770 ConstructionPhase
771 isEvaluatingConstructor(APValue::LValueBase Base,
772 ArrayRef<APValue::LValuePathEntry> Path) {
773 return ObjectsUnderConstruction.lookup({Base, Path});
774 }
775
776 /// If we're currently speculatively evaluating, the outermost call stack
777 /// depth at which we can mutate state, otherwise 0.
778 unsigned SpeculativeEvaluationDepth = 0;
779
780 /// The current array initialization index, if we're performing array
781 /// initialization.
782 uint64_t ArrayInitIndex = -1;
783
784 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
785 /// notes attached to it will also be stored, otherwise they will not be.
786 bool HasActiveDiagnostic;
787
788 /// Have we emitted a diagnostic explaining why we couldn't constant
789 /// fold (not just why it's not strictly a constant expression)?
790 bool HasFoldFailureDiagnostic;
791
792 /// Whether or not we're in a context where the front end requires a
793 /// constant value.
794 bool InConstantContext;
795
796 enum EvaluationMode {
797 /// Evaluate as a constant expression. Stop if we find that the expression
798 /// is not a constant expression.
799 EM_ConstantExpression,
800
801 /// Evaluate as a potential constant expression. Keep going if we hit a
802 /// construct that we can't evaluate yet (because we don't yet know the
803 /// value of something) but stop if we hit something that could never be
804 /// a constant expression.
805 EM_PotentialConstantExpression,
806
807 /// Fold the expression to a constant. Stop if we hit a side-effect that
808 /// we can't model.
809 EM_ConstantFold,
810
811 /// Evaluate the expression looking for integer overflow and similar
812 /// issues. Don't worry about side-effects, and try to visit all
813 /// subexpressions.
814 EM_EvaluateForOverflow,
815
816 /// Evaluate in any way we know how. Don't worry about side-effects that
817 /// can't be modeled.
818 EM_IgnoreSideEffects,
819
820 /// Evaluate as a constant expression. Stop if we find that the expression
821 /// is not a constant expression. Some expressions can be retried in the
822 /// optimizer if we don't constant fold them here, but in an unevaluated
823 /// context we try to fold them immediately since the optimizer never
824 /// gets a chance to look at it.
825 EM_ConstantExpressionUnevaluated,
826
827 /// Evaluate as a potential constant expression. Keep going if we hit a
828 /// construct that we can't evaluate yet (because we don't yet know the
829 /// value of something) but stop if we hit something that could never be
830 /// a constant expression. Some expressions can be retried in the
831 /// optimizer if we don't constant fold them here, but in an unevaluated
832 /// context we try to fold them immediately since the optimizer never
833 /// gets a chance to look at it.
834 EM_PotentialConstantExpressionUnevaluated,
835 } EvalMode;
836
837 /// Are we checking whether the expression is a potential constant
838 /// expression?
839 bool checkingPotentialConstantExpression() const {
840 return EvalMode == EM_PotentialConstantExpression ||
841 EvalMode == EM_PotentialConstantExpressionUnevaluated;
842 }
843
844 /// Are we checking an expression for overflow?
845 // FIXME: We should check for any kind of undefined or suspicious behavior
846 // in such constructs, not just overflow.
847 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
848
849 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
850 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
851 CallStackDepth(0), NextCallIndex(1),
852 StepsLeft(getLangOpts().ConstexprStepLimit),
853 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
854 EvaluatingDecl((const ValueDecl *)nullptr),
855 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
856 HasFoldFailureDiagnostic(false),
857 InConstantContext(false), EvalMode(Mode) {}
858
859 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
860 EvaluatingDecl = Base;
861 EvaluatingDeclValue = &Value;
862 }
863
864 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
865
866 bool CheckCallLimit(SourceLocation Loc) {
867 // Don't perform any constexpr calls (other than the call we're checking)
868 // when checking a potential constant expression.
869 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
870 return false;
871 if (NextCallIndex == 0) {
872 // NextCallIndex has wrapped around.
873 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
874 return false;
875 }
876 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
877 return true;
878 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
879 << getLangOpts().ConstexprCallDepth;
880 return false;
881 }
882
883 std::pair<CallStackFrame *, unsigned>
884 getCallFrameAndDepth(unsigned CallIndex) {
885 assert(CallIndex && "no call index in getCallFrameAndDepth");
886 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
887 // be null in this loop.
888 unsigned Depth = CallStackDepth;
889 CallStackFrame *Frame = CurrentCall;
890 while (Frame->Index > CallIndex) {
891 Frame = Frame->Caller;
892 --Depth;
893 }
894 if (Frame->Index == CallIndex)
895 return {Frame, Depth};
896 return {nullptr, 0};
897 }
898
899 bool nextStep(const Stmt *S) {
900 if (!StepsLeft) {
901 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
902 return false;
903 }
904 --StepsLeft;
905 return true;
906 }
907
908 private:
909 /// Add a diagnostic to the diagnostics list.
910 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
911 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
912 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
913 return EvalStatus.Diag->back().second;
914 }
915
916 /// Add notes containing a call stack to the current point of evaluation.
917 void addCallStack(unsigned Limit);
918
919 private:
920 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
921 unsigned ExtraNotes, bool IsCCEDiag) {
922
923 if (EvalStatus.Diag) {
924 // If we have a prior diagnostic, it will be noting that the expression
925 // isn't a constant expression. This diagnostic is more important,
926 // unless we require this evaluation to produce a constant expression.
927 //
928 // FIXME: We might want to show both diagnostics to the user in
929 // EM_ConstantFold mode.
930 if (!EvalStatus.Diag->empty()) {
931 switch (EvalMode) {
932 case EM_ConstantFold:
933 case EM_IgnoreSideEffects:
934 case EM_EvaluateForOverflow:
935 if (!HasFoldFailureDiagnostic)
936 break;
937 // We've already failed to fold something. Keep that diagnostic.
938 LLVM_FALLTHROUGH;
939 case EM_ConstantExpression:
940 case EM_PotentialConstantExpression:
941 case EM_ConstantExpressionUnevaluated:
942 case EM_PotentialConstantExpressionUnevaluated:
943 HasActiveDiagnostic = false;
944 return OptionalDiagnostic();
945 }
946 }
947
948 unsigned CallStackNotes = CallStackDepth - 1;
949 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
950 if (Limit)
951 CallStackNotes = std::min(CallStackNotes, Limit + 1);
952 if (checkingPotentialConstantExpression())
953 CallStackNotes = 0;
954
955 HasActiveDiagnostic = true;
956 HasFoldFailureDiagnostic = !IsCCEDiag;
957 EvalStatus.Diag->clear();
958 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
959 addDiag(Loc, DiagId);
960 if (!checkingPotentialConstantExpression())
961 addCallStack(Limit);
962 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
963 }
964 HasActiveDiagnostic = false;
965 return OptionalDiagnostic();
966 }
967 public:
968 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
969 OptionalDiagnostic
970 FFDiag(SourceLocation Loc,
971 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
972 unsigned ExtraNotes = 0) {
973 return Diag(Loc, DiagId, ExtraNotes, false);
974 }
975
976 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
977 = diag::note_invalid_subexpr_in_const_expr,
978 unsigned ExtraNotes = 0) {
979 if (EvalStatus.Diag)
980 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
981 HasActiveDiagnostic = false;
982 return OptionalDiagnostic();
983 }
984
985 /// Diagnose that the evaluation does not produce a C++11 core constant
986 /// expression.
987 ///
988 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
989 /// EM_PotentialConstantExpression mode and we produce one of these.
990 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
991 = diag::note_invalid_subexpr_in_const_expr,
992 unsigned ExtraNotes = 0) {
993 // Don't override a previous diagnostic. Don't bother collecting
994 // diagnostics if we're evaluating for overflow.
995 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
996 HasActiveDiagnostic = false;
997 return OptionalDiagnostic();
998 }
999 return Diag(Loc, DiagId, ExtraNotes, true);
1000 }
1001 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
1002 = diag::note_invalid_subexpr_in_const_expr,
1003 unsigned ExtraNotes = 0) {
1004 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
1005 }
1006 /// Add a note to a prior diagnostic.
1007 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
1008 if (!HasActiveDiagnostic)
1009 return OptionalDiagnostic();
1010 return OptionalDiagnostic(&addDiag(Loc, DiagId));
1011 }
1012
1013 /// Add a stack of notes to a prior diagnostic.
1014 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
1015 if (HasActiveDiagnostic) {
1016 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
1017 Diags.begin(), Diags.end());
1018 }
1019 }
1020
1021 /// Should we continue evaluation after encountering a side-effect that we
1022 /// couldn't model?
1023 bool keepEvaluatingAfterSideEffect() {
1024 switch (EvalMode) {
1025 case EM_PotentialConstantExpression:
1026 case EM_PotentialConstantExpressionUnevaluated:
1027 case EM_EvaluateForOverflow:
1028 case EM_IgnoreSideEffects:
1029 return true;
1030
1031 case EM_ConstantExpression:
1032 case EM_ConstantExpressionUnevaluated:
1033 case EM_ConstantFold:
1034 return false;
1035 }
1036 llvm_unreachable("Missed EvalMode case");
1037 }
1038
1039 /// Note that we have had a side-effect, and determine whether we should
1040 /// keep evaluating.
1041 bool noteSideEffect() {
1042 EvalStatus.HasSideEffects = true;
1043 return keepEvaluatingAfterSideEffect();
1044 }
1045
1046 /// Should we continue evaluation after encountering undefined behavior?
1047 bool keepEvaluatingAfterUndefinedBehavior() {
1048 switch (EvalMode) {
1049 case EM_EvaluateForOverflow:
1050 case EM_IgnoreSideEffects:
1051 case EM_ConstantFold:
1052 return true;
1053
1054 case EM_PotentialConstantExpression:
1055 case EM_PotentialConstantExpressionUnevaluated:
1056 case EM_ConstantExpression:
1057 case EM_ConstantExpressionUnevaluated:
1058 return false;
1059 }
1060 llvm_unreachable("Missed EvalMode case");
1061 }
1062
1063 /// Note that we hit something that was technically undefined behavior, but
1064 /// that we can evaluate past it (such as signed overflow or floating-point
1065 /// division by zero.)
1066 bool noteUndefinedBehavior() {
1067 EvalStatus.HasUndefinedBehavior = true;
1068 return keepEvaluatingAfterUndefinedBehavior();
1069 }
1070
1071 /// Should we continue evaluation as much as possible after encountering a
1072 /// construct which can't be reduced to a value?
1073 bool keepEvaluatingAfterFailure() {
1074 if (!StepsLeft)
1075 return false;
1076
1077 switch (EvalMode) {
1078 case EM_PotentialConstantExpression:
1079 case EM_PotentialConstantExpressionUnevaluated:
1080 case EM_EvaluateForOverflow:
1081 return true;
1082
1083 case EM_ConstantExpression:
1084 case EM_ConstantExpressionUnevaluated:
1085 case EM_ConstantFold:
1086 case EM_IgnoreSideEffects:
1087 return false;
1088 }
1089 llvm_unreachable("Missed EvalMode case");
1090 }
1091
1092 /// Notes that we failed to evaluate an expression that other expressions
1093 /// directly depend on, and determine if we should keep evaluating. This
1094 /// should only be called if we actually intend to keep evaluating.
1095 ///
1096 /// Call noteSideEffect() instead if we may be able to ignore the value that
1097 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1098 ///
1099 /// (Foo(), 1) // use noteSideEffect
1100 /// (Foo() || true) // use noteSideEffect
1101 /// Foo() + 1 // use noteFailure
1102 LLVM_NODISCARD bool noteFailure() {
1103 // Failure when evaluating some expression often means there is some
1104 // subexpression whose evaluation was skipped. Therefore, (because we
1105 // don't track whether we skipped an expression when unwinding after an
1106 // evaluation failure) every evaluation failure that bubbles up from a
1107 // subexpression implies that a side-effect has potentially happened. We
1108 // skip setting the HasSideEffects flag to true until we decide to
1109 // continue evaluating after that point, which happens here.
1110 bool KeepGoing = keepEvaluatingAfterFailure();
1111 EvalStatus.HasSideEffects |= KeepGoing;
1112 return KeepGoing;
1113 }
1114
1115 class ArrayInitLoopIndex {
1116 EvalInfo &Info;
1117 uint64_t OuterIndex;
1118
1119 public:
1120 ArrayInitLoopIndex(EvalInfo &Info)
1121 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1122 Info.ArrayInitIndex = 0;
1123 }
1124 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1125
1126 operator uint64_t&() { return Info.ArrayInitIndex; }
1127 };
1128 };
1129
1130 /// Object used to treat all foldable expressions as constant expressions.
1131 struct FoldConstant {
1132 EvalInfo &Info;
1133 bool Enabled;
1134 bool HadNoPriorDiags;
1135 EvalInfo::EvaluationMode OldMode;
1136
1137 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1138 : Info(Info),
1139 Enabled(Enabled),
1140 HadNoPriorDiags(Info.EvalStatus.Diag &&
1141 Info.EvalStatus.Diag->empty() &&
1142 !Info.EvalStatus.HasSideEffects),
1143 OldMode(Info.EvalMode) {
1144 if (Enabled &&
1145 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1146 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
1147 Info.EvalMode = EvalInfo::EM_ConstantFold;
1148 }
1149 void keepDiagnostics() { Enabled = false; }
1150 ~FoldConstant() {
1151 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1152 !Info.EvalStatus.HasSideEffects)
1153 Info.EvalStatus.Diag->clear();
1154 Info.EvalMode = OldMode;
1155 }
1156 };
1157
1158 /// RAII object used to set the current evaluation mode to ignore
1159 /// side-effects.
1160 struct IgnoreSideEffectsRAII {
1161 EvalInfo &Info;
1162 EvalInfo::EvaluationMode OldMode;
1163 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1164 : Info(Info), OldMode(Info.EvalMode) {
1165 if (!Info.checkingPotentialConstantExpression())
1166 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1167 }
1168
1169 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1170 };
1171
1172 /// RAII object used to optionally suppress diagnostics and side-effects from
1173 /// a speculative evaluation.
1174 class SpeculativeEvaluationRAII {
1175 EvalInfo *Info = nullptr;
1176 Expr::EvalStatus OldStatus;
1177 unsigned OldSpeculativeEvaluationDepth;
1178
1179 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1180 Info = Other.Info;
1181 OldStatus = Other.OldStatus;
1182 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1183 Other.Info = nullptr;
1184 }
1185
1186 void maybeRestoreState() {
1187 if (!Info)
1188 return;
1189
1190 Info->EvalStatus = OldStatus;
1191 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1192 }
1193
1194 public:
1195 SpeculativeEvaluationRAII() = default;
1196
1197 SpeculativeEvaluationRAII(
1198 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1199 : Info(&Info), OldStatus(Info.EvalStatus),
1200 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1201 Info.EvalStatus.Diag = NewDiag;
1202 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1203 }
1204
1205 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1206 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1207 moveFromAndCancel(std::move(Other));
1208 }
1209
1210 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1211 maybeRestoreState();
1212 moveFromAndCancel(std::move(Other));
1213 return *this;
1214 }
1215
1216 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1217 };
1218
1219 /// RAII object wrapping a full-expression or block scope, and handling
1220 /// the ending of the lifetime of temporaries created within it.
1221 template<bool IsFullExpression>
1222 class ScopeRAII {
1223 EvalInfo &Info;
1224 unsigned OldStackSize;
1225 public:
1226 ScopeRAII(EvalInfo &Info)
1227 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1228 // Push a new temporary version. This is needed to distinguish between
1229 // temporaries created in different iterations of a loop.
1230 Info.CurrentCall->pushTempVersion();
1231 }
1232 ~ScopeRAII() {
1233 // Body moved to a static method to encourage the compiler to inline away
1234 // instances of this class.
1235 cleanup(Info, OldStackSize);
1236 Info.CurrentCall->popTempVersion();
1237 }
1238 private:
1239 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1240 unsigned NewEnd = OldStackSize;
1241 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1242 I != N; ++I) {
1243 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1244 // Full-expression cleanup of a lifetime-extended temporary: nothing
1245 // to do, just move this cleanup to the right place in the stack.
1246 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1247 ++NewEnd;
1248 } else {
1249 // End the lifetime of the object.
1250 Info.CleanupStack[I].endLifetime();
1251 }
1252 }
1253 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1254 Info.CleanupStack.end());
1255 }
1256 };
1257 typedef ScopeRAII<false> BlockScopeRAII;
1258 typedef ScopeRAII<true> FullExpressionRAII;
1259 void GetIntCapLValue(APValue &Value, QualType QT, ASTContext &Ctx){
1260 if (Value.isInt() && QT->isCHERICapabilityType(Ctx)) {
1261 APValue::LValueBase Base;
1262 APSInt Val = Value.getInt();
1263 CharUnits Size = CharUnits::fromQuantity(Val.isNegative() ?
1264 Val.getSExtValue() : Val.getZExtValue());
1265 Value = APValue(Base, Size, APValue::NoLValuePath(), 0);
1266 }
1267 }
1268}
1269
1270bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1271 CheckSubobjectKind CSK) {
1272 if (Invalid)
1273 return false;
1274 if (isOnePastTheEnd()) {
1275 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1276 << CSK;
1277 setInvalid();
1278 return false;
1279 }
1280 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1281 // must actually be at least one array element; even a VLA cannot have a
1282 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1283 return true;
1284}
1285
1286void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1287 const Expr *E) {
1288 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1289 // Do not set the designator as invalid: we can represent this situation,
1290 // and correct handling of __builtin_object_size requires us to do so.
1291}
1292
1293void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1294 const Expr *E,
1295 const APSInt &N) {
1296 // If we're complaining, we must be able to statically determine the size of
1297 // the most derived array.
1298 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1299 Info.CCEDiag(E, diag::note_constexpr_array_index)
1300 << N << /*array*/ 0
1301 << static_cast<unsigned>(getMostDerivedArraySize());
1302 else
1303 Info.CCEDiag(E, diag::note_constexpr_array_index)
1304 << N << /*non-array*/ 1;
1305 setInvalid();
1306}
1307
1308CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1309 const FunctionDecl *Callee, const LValue *This,
1310 APValue *Arguments)
1311 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1312 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1313 Info.CurrentCall = this;
1314 ++Info.CallStackDepth;
1315}
1316
1317CallStackFrame::~CallStackFrame() {
1318 assert(Info.CurrentCall == this && "calls retired out of order");
1319 --Info.CallStackDepth;
1320 Info.CurrentCall = Caller;
1321}
1322
1323APValue &CallStackFrame::createTemporary(const void *Key,
1324 bool IsLifetimeExtended) {
1325 unsigned Version = Info.CurrentCall->getTempVersion();
1326 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1327 assert(Result.isAbsent() && "temporary created multiple times");
1328 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1329 return Result;
1330}
1331
1332static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1333
1334void EvalInfo::addCallStack(unsigned Limit) {
1335 // Determine which calls to skip, if any.
1336 unsigned ActiveCalls = CallStackDepth - 1;
1337 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1338 if (Limit && Limit < ActiveCalls) {
1339 SkipStart = Limit / 2 + Limit % 2;
1340 SkipEnd = ActiveCalls - Limit / 2;
1341 }
1342
1343 // Walk the call stack and add the diagnostics.
1344 unsigned CallIdx = 0;
1345 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1346 Frame = Frame->Caller, ++CallIdx) {
1347 // Skip this call?
1348 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1349 if (CallIdx == SkipStart) {
1350 // Note that we're skipping calls.
1351 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1352 << unsigned(ActiveCalls - Limit);
1353 }
1354 continue;
1355 }
1356
1357 // Use a different note for an inheriting constructor, because from the
1358 // user's perspective it's not really a function at all.
1359 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1360 if (CD->isInheritingConstructor()) {
1361 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1362 << CD->getParent();
1363 continue;
1364 }
1365 }
1366
1367 SmallVector<char, 128> Buffer;
1368 llvm::raw_svector_ostream Out(Buffer);
1369 describeCall(Frame, Out);
1370 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1371 }
1372}
1373
1374/// Kinds of access we can perform on an object, for diagnostics. Note that
1375/// we consider a member function call to be a kind of access, even though
1376/// it is not formally an access of the object, because it has (largely) the
1377/// same set of semantic restrictions.
1378enum AccessKinds {
1379 AK_Read,
1380 AK_Assign,
1381 AK_Increment,
1382 AK_Decrement,
1383 AK_MemberCall,
1384 AK_DynamicCast,
1385 AK_TypeId,
1386};
1387
1388static bool isModification(AccessKinds AK) {
1389 switch (AK) {
1390 case AK_Read:
1391 case AK_MemberCall:
1392 case AK_DynamicCast:
1393 case AK_TypeId:
1394 return false;
1395 case AK_Assign:
1396 case AK_Increment:
1397 case AK_Decrement:
1398 return true;
1399 }
1400 llvm_unreachable("unknown access kind");
1401}
1402
1403/// Is this an access per the C++ definition?
1404static bool isFormalAccess(AccessKinds AK) {
1405 return AK == AK_Read || isModification(AK);
1406}
1407
1408namespace {
1409 struct ComplexValue {
1410 private:
1411 bool IsInt;
1412
1413 public:
1414 APSInt IntReal, IntImag;
1415 APFloat FloatReal, FloatImag;
1416
1417 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1418
1419 void makeComplexFloat() { IsInt = false; }
1420 bool isComplexFloat() const { return !IsInt; }
1421 APFloat &getComplexFloatReal() { return FloatReal; }
1422 APFloat &getComplexFloatImag() { return FloatImag; }
1423
1424 void makeComplexInt() { IsInt = true; }
1425 bool isComplexInt() const { return IsInt; }
1426 APSInt &getComplexIntReal() { return IntReal; }
1427 APSInt &getComplexIntImag() { return IntImag; }
1428
1429 void moveInto(APValue &v) const {
1430 if (isComplexFloat())
1431 v = APValue(FloatReal, FloatImag);
1432 else
1433 v = APValue(IntReal, IntImag);
1434 }
1435 void setFrom(const APValue &v) {
1436 assert(v.isComplexFloat() || v.isComplexInt());
1437 if (v.isComplexFloat()) {
1438 makeComplexFloat();
1439 FloatReal = v.getComplexFloatReal();
1440 FloatImag = v.getComplexFloatImag();
1441 } else {
1442 makeComplexInt();
1443 IntReal = v.getComplexIntReal();
1444 IntImag = v.getComplexIntImag();
1445 }
1446 }
1447 };
1448
1449 struct LValue {
1450 APValue::LValueBase Base;
1451 CharUnits Offset;
1452 SubobjectDesignator Designator;
1453 bool IsNullPtr : 1;
1454 bool InvalidBase : 1;
1455
1456 const APValue::LValueBase getLValueBase() const { return Base; }
1457 CharUnits &getLValueOffset() { return Offset; }
1458 const CharUnits &getLValueOffset() const { return Offset; }
1459 SubobjectDesignator &getLValueDesignator() { return Designator; }
1460 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1461 bool isNullPointer() const { return IsNullPtr;}
1462
1463 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1464 unsigned getLValueVersion() const { return Base.getVersion(); }
1465
1466 void moveInto(APValue &V) const {
1467 if (Designator.Invalid)
1468 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1469 else {
1470 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1471 V = APValue(Base, Offset, Designator.Entries,
1472 Designator.IsOnePastTheEnd, IsNullPtr);
1473 }
1474 }
1475 void setFrom(ASTContext &Ctx, const APValue &V) {
1476 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1477 Base = V.getLValueBase();
1478 Offset = V.getLValueOffset();
1479 InvalidBase = false;
1480 Designator = SubobjectDesignator(Ctx, V);
1481 IsNullPtr = V.isNullPointer();
1482 }
1483
1484 void set(APValue::LValueBase B, bool BInvalid = false) {
1485#ifndef NDEBUG
1486 // We only allow a few types of invalid bases. Enforce that here.
1487 if (BInvalid) {
1488 const auto *E = B.get<const Expr *>();
1489 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1490 "Unexpected type of invalid base");
1491 }
1492#endif
1493
1494 Base = B;
1495 Offset = CharUnits::fromQuantity(0);
1496 InvalidBase = BInvalid;
1497 Designator = SubobjectDesignator(getType(B));
1498 IsNullPtr = false;
1499 }
1500
1501 void setNull(QualType PointerTy, uint64_t TargetVal) {
1502 Base = (Expr *)nullptr;
1503 Offset = CharUnits::fromQuantity(TargetVal);
1504 InvalidBase = false;
1505 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1506 IsNullPtr = true;
1507 }
1508
1509 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1510 set(B, true);
1511 }
1512
1513 private:
1514 // Check that this LValue is not based on a null pointer. If it is, produce
1515 // a diagnostic and mark the designator as invalid.
1516 template <typename GenDiagType>
1517 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1518 if (Designator.Invalid)
1519 return false;
1520 if (IsNullPtr) {
1521 GenDiag();
1522 Designator.setInvalid();
1523 return false;
1524 }
1525 return true;
1526 }
1527
1528 public:
1529 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1530 CheckSubobjectKind CSK) {
1531 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1532 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1533 });
1534 }
1535
1536 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1537 AccessKinds AK) {
1538 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1539 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1540 });
1541 }
1542
1543 // Check this LValue refers to an object. If not, set the designator to be
1544 // invalid and emit a diagnostic.
1545 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1546 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1547 Designator.checkSubobject(Info, E, CSK);
1548 }
1549
1550 void addDecl(EvalInfo &Info, const Expr *E,
1551 const Decl *D, bool Virtual = false) {
1552 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1553 Designator.addDeclUnchecked(D, Virtual);
1554 }
1555 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1556 if (!Designator.Entries.empty()) {
1557 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1558 Designator.setInvalid();
1559 return;
1560 }
1561 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1562 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1563 Designator.FirstEntryIsAnUnsizedArray = true;
1564 Designator.addUnsizedArrayUnchecked(ElemTy);
1565 }
1566 }
1567 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1568 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1569 Designator.addArrayUnchecked(CAT);
1570 }
1571 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1572 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1573 Designator.addComplexUnchecked(EltTy, Imag);
1574 }
1575 void clearIsNullPointer() {
1576 IsNullPtr = false;
1577 }
1578 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1579 const APSInt &Index, CharUnits ElementSize) {
1580 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1581 // but we're not required to diagnose it and it's valid in C++.)
1582 if (!Index)
1583 return;
1584
1585 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1586 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1587 // offsets.
1588 uint64_t Offset64 = Offset.getQuantity();
1589 uint64_t ElemSize64 = ElementSize.getQuantity();
1590 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1591 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1592
1593 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1594 Designator.adjustIndex(Info, E, Index);
1595 clearIsNullPointer();
1596 }
1597 void adjustOffset(CharUnits N) {
1598 Offset += N;
1599 if (N.getQuantity())
1600 clearIsNullPointer();
1601 }
1602 };
1603
1604 struct MemberPtr {
1605 MemberPtr() {}
1606 explicit MemberPtr(const ValueDecl *Decl) :
1607 DeclAndIsDerivedMember(Decl, false), Path() {}
1608
1609 /// The member or (direct or indirect) field referred to by this member
1610 /// pointer, or 0 if this is a null member pointer.
1611 const ValueDecl *getDecl() const {
1612 return DeclAndIsDerivedMember.getPointer();
1613 }
1614 /// Is this actually a member of some type derived from the relevant class?
1615 bool isDerivedMember() const {
1616 return DeclAndIsDerivedMember.getInt();
1617 }
1618 /// Get the class which the declaration actually lives in.
1619 const CXXRecordDecl *getContainingRecord() const {
1620 return cast<CXXRecordDecl>(
1621 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1622 }
1623
1624 void moveInto(APValue &V) const {
1625 V = APValue(getDecl(), isDerivedMember(), Path);
1626 }
1627 void setFrom(const APValue &V) {
1628 assert(V.isMemberPointer());
1629 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1630 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1631 Path.clear();
1632 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1633 Path.insert(Path.end(), P.begin(), P.end());
1634 }
1635
1636 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1637 /// whether the member is a member of some class derived from the class type
1638 /// of the member pointer.
1639 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1640 /// Path - The path of base/derived classes from the member declaration's
1641 /// class (exclusive) to the class type of the member pointer (inclusive).
1642 SmallVector<const CXXRecordDecl*, 4> Path;
1643
1644 /// Perform a cast towards the class of the Decl (either up or down the
1645 /// hierarchy).
1646 bool castBack(const CXXRecordDecl *Class) {
1647 assert(!Path.empty());
1648 const CXXRecordDecl *Expected;
1649 if (Path.size() >= 2)
1650 Expected = Path[Path.size() - 2];
1651 else
1652 Expected = getContainingRecord();
1653 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1654 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1655 // if B does not contain the original member and is not a base or
1656 // derived class of the class containing the original member, the result
1657 // of the cast is undefined.
1658 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1659 // (D::*). We consider that to be a language defect.
1660 return false;
1661 }
1662 Path.pop_back();
1663 return true;
1664 }
1665 /// Perform a base-to-derived member pointer cast.
1666 bool castToDerived(const CXXRecordDecl *Derived) {
1667 if (!getDecl())
1668 return true;
1669 if (!isDerivedMember()) {
1670 Path.push_back(Derived);
1671 return true;
1672 }
1673 if (!castBack(Derived))
1674 return false;
1675 if (Path.empty())
1676 DeclAndIsDerivedMember.setInt(false);
1677 return true;
1678 }
1679 /// Perform a derived-to-base member pointer cast.
1680 bool castToBase(const CXXRecordDecl *Base) {
1681 if (!getDecl())
1682 return true;
1683 if (Path.empty())
1684 DeclAndIsDerivedMember.setInt(true);
1685 if (isDerivedMember()) {
1686 Path.push_back(Base);
1687 return true;
1688 }
1689 return castBack(Base);
1690 }
1691 };
1692
1693 /// Compare two member pointers, which are assumed to be of the same type.
1694 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1695 if (!LHS.getDecl() || !RHS.getDecl())
1696 return !LHS.getDecl() && !RHS.getDecl();
1697 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1698 return false;
1699 return LHS.Path == RHS.Path;
1700 }
1701}
1702
1703static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1704static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1705 const LValue &This, const Expr *E,
1706 bool AllowNonLiteralTypes = false);
1707static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1708 bool InvalidBaseOK = false);
1709static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1710 bool InvalidBaseOK = false);
1711static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1712 EvalInfo &Info);
1713static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1714static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1715static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1716 EvalInfo &Info);
1717static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1718static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1719static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1720 EvalInfo &Info);
1721static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1722
1723/// Evaluate an integer or fixed point expression into an APResult.
1724static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1725 EvalInfo &Info);
1726
1727/// Evaluate only a fixed point expression into an APResult.
1728static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1729 EvalInfo &Info);
1730
1731//===----------------------------------------------------------------------===//
1732// Misc utilities
1733//===----------------------------------------------------------------------===//
1734
1735/// A helper function to create a temporary and set an LValue.
1736template <class KeyTy>
1737static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1738 LValue &LV, CallStackFrame &Frame) {
1739 LV.set({Key, Frame.Info.CurrentCall->Index,
1740 Frame.Info.CurrentCall->getTempVersion()});
1741 return Frame.createTemporary(Key, IsLifetimeExtended);
1742}
1743
1744/// Negate an APSInt in place, converting it to a signed form if necessary, and
1745/// preserving its value (by extending by up to one bit as needed).
1746static void negateAsSigned(APSInt &Int) {
1747 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1748 Int = Int.extend(Int.getBitWidth() + 1);
1749 Int.setIsSigned(true);
1750 }
1751 Int = -Int;
1752}
1753
1754/// Produce a string describing the given constexpr call.
1755static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1756 unsigned ArgIndex = 0;
1757 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1758 !isa<CXXConstructorDecl>(Frame->Callee) &&
1759 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1760
1761 if (!IsMemberCall)
1762 Out << *Frame->Callee << '(';
1763
1764 if (Frame->This && IsMemberCall) {
1765 APValue Val;
1766 Frame->This->moveInto(Val);
1767 Val.printPretty(Out, Frame->Info.Ctx,
1768 Frame->This->Designator.MostDerivedType);
1769 // FIXME: Add parens around Val if needed.
1770 Out << "->" << *Frame->Callee << '(';
1771 IsMemberCall = false;
1772 }
1773
1774 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1775 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1776 if (ArgIndex > (unsigned)IsMemberCall)
1777 Out << ", ";
1778
1779 const ParmVarDecl *Param = *I;
1780 const APValue &Arg = Frame->Arguments[ArgIndex];
1781 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1782
1783 if (ArgIndex == 0 && IsMemberCall)
1784 Out << "->" << *Frame->Callee << '(';
1785 }
1786
1787 Out << ')';
1788}
1789
1790/// Evaluate an expression to see if it had side-effects, and discard its
1791/// result.
1792/// \return \c true if the caller should keep evaluating.
1793static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1794 APValue Scratch;
1795 if (!Evaluate(Scratch, Info, E))
1796 // We don't need the value, but we might have skipped a side effect here.
1797 return Info.noteSideEffect();
1798 return true;
1799}
1800
1801/// Should this call expression be treated as a string literal?
1802static bool IsStringLiteralCall(const CallExpr *E) {
1803 unsigned Builtin = E->getBuiltinCallee();
1804 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1805 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1806}
1807
1808static bool IsGlobalLValue(APValue::LValueBase B) {
1809 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1810 // constant expression of pointer type that evaluates to...
1811
1812 // ... a null pointer value, or a prvalue core constant expression of type
1813 // std::nullptr_t.
1814 if (!B) return true;
1815
1816 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1817 // ... the address of an object with static storage duration,
1818 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1819 return VD->hasGlobalStorage();
1820 // ... the address of a function,
1821 return isa<FunctionDecl>(D);
1822 }
1823
1824 if (B.is<TypeInfoLValue>())
1825 return true;
1826
1827 const Expr *E = B.get<const Expr*>();
1828 switch (E->getStmtClass()) {
1829 default:
1830 return false;
1831 case Expr::CompoundLiteralExprClass: {
1832 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1833 return CLE->isFileScope() && CLE->isLValue();
1834 }
1835 case Expr::MaterializeTemporaryExprClass:
1836 // A materialized temporary might have been lifetime-extended to static
1837 // storage duration.
1838 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1839 // A string literal has static storage duration.
1840 case Expr::StringLiteralClass:
1841 case Expr::PredefinedExprClass:
1842 case Expr::ObjCStringLiteralClass:
1843 case Expr::ObjCEncodeExprClass:
1844 case Expr::CXXUuidofExprClass:
1845 return true;
1846 case Expr::ObjCBoxedExprClass:
1847 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
1848 case Expr::CallExprClass:
1849 return IsStringLiteralCall(cast<CallExpr>(E));
1850 // For GCC compatibility, &&label has static storage duration.
1851 case Expr::AddrLabelExprClass:
1852 return true;
1853 // A Block literal expression may be used as the initialization value for
1854 // Block variables at global or local static scope.
1855 case Expr::BlockExprClass:
1856 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1857 case Expr::ImplicitValueInitExprClass:
1858 // FIXME:
1859 // We can never form an lvalue with an implicit value initialization as its
1860 // base through expression evaluation, so these only appear in one case: the
1861 // implicit variable declaration we invent when checking whether a constexpr
1862 // constructor can produce a constant expression. We must assume that such
1863 // an expression might be a global lvalue.
1864 return true;
1865 }
1866}
1867
1868static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1869 return LVal.Base.dyn_cast<const ValueDecl*>();
1870}
1871
1872static bool IsLiteralLValue(const LValue &Value) {
1873 if (Value.getLValueCallIndex())
1874 return false;
1875 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1876 return E && !isa<MaterializeTemporaryExpr>(E);
1877}
1878
1879static bool IsWeakLValue(const LValue &Value) {
1880 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1881 return Decl && Decl->isWeak();
1882}
1883
1884static bool isZeroSized(const LValue &Value) {
1885 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1886 if (Decl && isa<VarDecl>(Decl)) {
1887 QualType Ty = Decl->getType();
1888 if (Ty->isArrayType())
1889 return Ty->isIncompleteType() ||
1890 Decl->getASTContext().getTypeSize(Ty) == 0;
1891 }
1892 return false;
1893}
1894
1895static bool HasSameBase(const LValue &A, const LValue &B) {
1896 if (!A.getLValueBase())
1897 return !B.getLValueBase();
1898 if (!B.getLValueBase())
1899 return false;
1900
1901 if (A.getLValueBase().getOpaqueValue() !=
1902 B.getLValueBase().getOpaqueValue()) {
1903 const Decl *ADecl = GetLValueBaseDecl(A);
1904 if (!ADecl)
1905 return false;
1906 const Decl *BDecl = GetLValueBaseDecl(B);
1907 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1908 return false;
1909 }
1910
1911 return IsGlobalLValue(A.getLValueBase()) ||
1912 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1913 A.getLValueVersion() == B.getLValueVersion());
1914}
1915
1916static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1917 assert(Base && "no location for a null lvalue");
1918 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1919 if (VD)
1920 Info.Note(VD->getLocation(), diag::note_declared_at);
1921 else if (const Expr *E = Base.dyn_cast<const Expr*>())
1922 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1923 // We have no information to show for a typeid(T) object.
1924}
1925
1926/// Check that this reference or pointer core constant expression is a valid
1927/// value for an address or reference constant expression. Return true if we
1928/// can fold this expression, whether or not it's a constant expression.
1929static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1930 QualType Type, const LValue &LVal,
1931 Expr::ConstExprUsage Usage) {
1932 bool IsReferenceType = Type->isReferenceType();
1933
1934 APValue::LValueBase Base = LVal.getLValueBase();
1935 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1936
1937 // Check that the object is a global. Note that the fake 'this' object we
1938 // manufacture when checking potential constant expressions is conservatively
1939 // assumed to be global here.
1940 if (!IsGlobalLValue(Base)) {
1941 if (Info.getLangOpts().CPlusPlus11) {
1942 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1943 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1944 << IsReferenceType << !Designator.Entries.empty()
1945 << !!VD << VD;
1946 NoteLValueLocation(Info, Base);
1947 } else {
1948 Info.FFDiag(Loc);
1949 }
1950 // Don't allow references to temporaries to escape.
1951 return false;
1952 }
1953 assert((Info.checkingPotentialConstantExpression() ||
1954 LVal.getLValueCallIndex() == 0) &&
1955 "have call index for global lvalue");
1956
1957 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1958 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1959 // Check if this is a thread-local variable.
1960 if (Var->getTLSKind())
1961 return false;
1962
1963 // A dllimport variable never acts like a constant.
1964 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
1965 return false;
1966 }
1967 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1968 // __declspec(dllimport) must be handled very carefully:
1969 // We must never initialize an expression with the thunk in C++.
1970 // Doing otherwise would allow the same id-expression to yield
1971 // different addresses for the same function in different translation
1972 // units. However, this means that we must dynamically initialize the
1973 // expression with the contents of the import address table at runtime.
1974 //
1975 // The C language has no notion of ODR; furthermore, it has no notion of
1976 // dynamic initialization. This means that we are permitted to
1977 // perform initialization with the address of the thunk.
1978 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1979 FD->hasAttr<DLLImportAttr>())
1980 return false;
1981 }
1982 }
1983
1984 // Allow address constant expressions to be past-the-end pointers. This is
1985 // an extension: the standard requires them to point to an object.
1986 if (!IsReferenceType)
1987 return true;
1988
1989 // A reference constant expression must refer to an object.
1990 if (!Base) {
1991 // FIXME: diagnostic
1992 Info.CCEDiag(Loc);
1993 return true;
1994 }
1995
1996 // Does this refer one past the end of some object?
1997 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1998 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1999 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2000 << !Designator.Entries.empty() << !!VD << VD;
2001 NoteLValueLocation(Info, Base);
2002 }
2003
2004 return true;
2005}
2006
2007/// Member pointers are constant expressions unless they point to a
2008/// non-virtual dllimport member function.
2009static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2010 SourceLocation Loc,
2011 QualType Type,
2012 const APValue &Value,
2013 Expr::ConstExprUsage Usage) {
2014 const ValueDecl *Member = Value.getMemberPointerDecl();
2015 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2016 if (!FD)
2017 return true;
2018 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2019 !FD->hasAttr<DLLImportAttr>();
2020}
2021
2022/// Check that this core constant expression is of literal type, and if not,
2023/// produce an appropriate diagnostic.
2024static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2025 const LValue *This = nullptr) {
2026 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2027 return true;
2028
2029 // C++1y: A constant initializer for an object o [...] may also invoke
2030 // constexpr constructors for o and its subobjects even if those objects
2031 // are of non-literal class types.
2032 //
2033 // C++11 missed this detail for aggregates, so classes like this:
2034 // struct foo_t { union { int i; volatile int j; } u; };
2035 // are not (obviously) initializable like so:
2036 // __attribute__((__require_constant_initialization__))
2037 // static const foo_t x = {{0}};
2038 // because "i" is a subobject with non-literal initialization (due to the
2039 // volatile member of the union). See:
2040 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2041 // Therefore, we use the C++1y behavior.
2042 if (This && Info.EvaluatingDecl == This->getLValueBase())
2043 return true;
2044
2045 // Prvalue constant expressions must be of literal types.
2046 if (Info.getLangOpts().CPlusPlus11)
2047 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2048 << E->getType();
2049 else
2050 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2051 return false;
2052}
2053
2054/// Check that this core constant expression value is a valid value for a
2055/// constant expression. If not, report an appropriate diagnostic. Does not
2056/// check that the expression is of literal type.
2057static bool
2058CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2059 const APValue &Value,
2060 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen,
2061 SourceLocation SubobjectLoc = SourceLocation()) {
2062 if (!Value.hasValue()) {
2063 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2064 << true << Type;
2065 if (SubobjectLoc.isValid())
2066 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2067 return false;
2068 }
2069
2070 // We allow _Atomic(T) to be initialized from anything that T can be
2071 // initialized from.
2072 if (const AtomicType *AT = Type->getAs<AtomicType>())
2073 Type = AT->getValueType();
2074
2075 // Core issue 1454: For a literal constant expression of array or class type,
2076 // each subobject of its value shall have been initialized by a constant
2077 // expression.
2078 if (Value.isArray()) {
2079 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2080 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2081 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
2082 Value.getArrayInitializedElt(I), Usage,
2083 SubobjectLoc))
2084 return false;
2085 }
2086 if (!Value.hasArrayFiller())
2087 return true;
2088 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
2089 Usage, SubobjectLoc);
2090 }
2091 if (Value.isUnion() && Value.getUnionField()) {
2092 return CheckConstantExpression(Info, DiagLoc,
2093 Value.getUnionField()->getType(),
2094 Value.getUnionValue(), Usage,
2095 Value.getUnionField()->getLocation());
2096 }
2097 if (Value.isStruct()) {
2098 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2099 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2100 unsigned BaseIndex = 0;
2101 for (const CXXBaseSpecifier &BS : CD->bases()) {
2102 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
2103 Value.getStructBase(BaseIndex), Usage,
2104 BS.getBeginLoc()))
2105 return false;
2106 ++BaseIndex;
2107 }
2108 }
2109 for (const auto *I : RD->fields()) {
2110 if (I->isUnnamedBitfield())
2111 continue;
2112
2113 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
2114 Value.getStructField(I->getFieldIndex()),
2115 Usage, I->getLocation()))
2116 return false;
2117 }
2118 }
2119
2120 if (Value.isLValue()) {
2121 LValue LVal;
2122 LVal.setFrom(Info.Ctx, Value);
2123 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
2124 }
2125
2126 if (Value.isMemberPointer())
2127 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2128
2129 // Everything else is fine.
2130 return true;
2131}
2132
2133static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2134 // A null base expression indicates a null pointer. These are always
2135 // evaluatable, and they are false unless the offset is zero.
2136 if (!Value.getLValueBase()) {
2137 Result = !Value.getLValueOffset().isZero();
2138 return true;
2139 }
2140
2141 // We have a non-null base. These are generally known to be true, but if it's
2142 // a weak declaration it can be null at runtime.
2143 Result = true;
2144 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2145 return !Decl || !Decl->isWeak();
2146}
2147
2148static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2149 switch (Val.getKind()) {
2150 case APValue::None:
2151 case APValue::Indeterminate:
2152 return false;
2153 case APValue::Int:
2154 Result = Val.getInt().getBoolValue();
2155 return true;
2156 case APValue::FixedPoint:
2157 Result = Val.getFixedPoint().getBoolValue();
2158 return true;
2159 case APValue::Float:
2160 Result = !Val.getFloat().isZero();
2161 return true;
2162 case APValue::ComplexInt:
2163 Result = Val.getComplexIntReal().getBoolValue() ||
2164 Val.getComplexIntImag().getBoolValue();
2165 return true;
2166 case APValue::ComplexFloat:
2167 Result = !Val.getComplexFloatReal().isZero() ||
2168 !Val.getComplexFloatImag().isZero();
2169 return true;
2170 case APValue::LValue:
2171 return EvalPointerValueAsBool(Val, Result);
2172 case APValue::MemberPointer:
2173 Result = Val.getMemberPointerDecl();
2174 return true;
2175 case APValue::Vector:
2176 case APValue::Array:
2177 case APValue::Struct:
2178 case APValue::Union:
2179 case APValue::AddrLabelDiff:
2180 return false;
2181 }
2182
2183 llvm_unreachable("unknown APValue kind");
2184}
2185
2186static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2187 EvalInfo &Info) {
2188 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2189 APValue Val;
2190 if (!Evaluate(Val, Info, E))
2191 return false;
2192 return HandleConversionToBool(Val, Result);
2193}
2194
2195template<typename T>
2196static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2197 const T &SrcValue, QualType DestType) {
2198 Info.CCEDiag(E, diag::note_constexpr_overflow)
2199 << SrcValue << DestType;
2200 return Info.noteUndefinedBehavior();
2201}
2202
2203static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2204 QualType SrcType, const APFloat &Value,
2205 QualType DestType, APSInt &Result) {
2206 unsigned DestWidth = Info.Ctx.getIntRange(DestType);
2207 // Determine whether we are converting to unsigned or signed.
2208 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2209
2210 Result = APSInt(DestWidth, !DestSigned);
2211 bool ignored;
2212 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2213 & APFloat::opInvalidOp)
2214 return HandleOverflow(Info, E, Value, DestType);
2215 return true;
2216}
2217
2218static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2219 QualType SrcType, QualType DestType,
2220 APFloat &Result) {
2221 APFloat Value = Result;
2222 bool ignored;
2223 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2224 APFloat::rmNearestTiesToEven, &ignored)
2225 & APFloat::opOverflow)
2226 return HandleOverflow(Info, E, Value, DestType);
2227 return true;
2228}
2229
2230static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2231 QualType DestType, QualType SrcType,
2232 const APSInt &Value) {
2233 unsigned DestWidth = Info.Ctx.getIntRange(DestType);
2234 // Figure out if this is a truncate, extend or noop cast.
2235 // If the input is signed, do a sign extend, noop, or truncate.
2236 APSInt Result = Value.extOrTrunc(DestWidth);
2237 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2238 if (DestType->isBooleanType())
2239 Result = Value.getBoolValue();
2240 return Result;
2241}
2242
2243static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2244 QualType SrcType, const APSInt &Value,
2245 QualType DestType, APFloat &Result) {
2246 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2247 if (Result.convertFromAPInt(Value, Value.isSigned(),
2248 APFloat::rmNearestTiesToEven)
2249 & APFloat::opOverflow)
2250 return HandleOverflow(Info, E, Value, DestType);
2251 return true;
2252}
2253
2254static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2255 APValue &Value, const FieldDecl *FD) {
2256 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2257
2258 if (!Value.isInt()) {
2259 // Trying to store a pointer-cast-to-integer into a bitfield.
2260 // FIXME: In this case, we should provide the diagnostic for casting
2261 // a pointer to an integer.
2262 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2263 Info.FFDiag(E);
2264 return false;
2265 }
2266
2267 APSInt &Int = Value.getInt();
2268 unsigned OldBitWidth = Int.getBitWidth();
2269 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2270 if (NewBitWidth < OldBitWidth)
2271 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2272 return true;
2273}
2274
2275static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2276 llvm::APInt &Res) {
2277 APValue SVal;
2278 if (!Evaluate(SVal, Info, E))
2279 return false;
2280 if (SVal.isInt()) {
2281 Res = SVal.getInt();
2282 return true;
2283 }
2284 if (SVal.isFloat()) {
2285 Res = SVal.getFloat().bitcastToAPInt();
2286 return true;
2287 }
2288 if (SVal.isVector()) {
2289 QualType VecTy = E->getType();
2290 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2291 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2292 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2293 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2294 Res = llvm::APInt::getNullValue(VecSize);
2295 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2296 APValue &Elt = SVal.getVectorElt(i);
2297 llvm::APInt EltAsInt;
2298 if (Elt.isInt()) {
2299 EltAsInt = Elt.getInt();
2300 } else if (Elt.isFloat()) {
2301 EltAsInt = Elt.getFloat().bitcastToAPInt();
2302 } else {
2303 // Don't try to handle vectors of anything other than int or float
2304 // (not sure if it's possible to hit this case).
2305 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2306 return false;
2307 }
2308 unsigned BaseEltSize = EltAsInt.getBitWidth();
2309 if (BigEndian)
2310 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2311 else
2312 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2313 }
2314 return true;
2315 }
2316 // Give up if the input isn't an int, float, or vector. For example, we
2317 // reject "(v4i16)(intptr_t)&a".
2318 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2319 return false;
2320}
2321
2322/// Perform the given integer operation, which is known to need at most BitWidth
2323/// bits, and check for overflow in the original type (if that type was not an
2324/// unsigned type).
2325template<typename Operation>
2326static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2327 const APSInt &LHS, const APSInt &RHS,
2328 unsigned BitWidth, Operation Op,
2329 APSInt &Result) {
2330 if (LHS.isUnsigned()) {
2331 Result = Op(LHS, RHS);
2332 return true;
2333 }
2334
2335 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2336 Result = Value.trunc(LHS.getBitWidth());
2337 if (Result.extend(BitWidth) != Value) {
2338 if (Info.checkingForOverflow())
2339 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2340 diag::warn_integer_constant_overflow)
2341 << Result.toString(10) << E->getType();
2342 else
2343 return HandleOverflow(Info, E, Value, E->getType());
2344 }
2345 return true;
2346}
2347
2348/// Perform the given binary integer operation.
2349static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2350 BinaryOperatorKind Opcode, APSInt RHS,
2351 APSInt &Result) {
2352 switch (Opcode) {
2353 default:
2354 Info.FFDiag(E);
2355 return false;
2356 case BO_Mul:
2357 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2358 std::multiplies<APSInt>(), Result);
2359 case BO_Add:
2360 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2361 std::plus<APSInt>(), Result);
2362 case BO_Sub:
2363 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2364 std::minus<APSInt>(), Result);
2365 case BO_And: Result = LHS & RHS; return true;
2366 case BO_Xor: Result = LHS ^ RHS; return true;
2367 case BO_Or: Result = LHS | RHS; return true;
2368 case BO_Div:
2369 case BO_Rem:
2370 if (RHS == 0) {
2371 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2372 return false;
2373 }
2374 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2375 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2376 // this operation and gives the two's complement result.
2377 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2378 LHS.isSigned() && LHS.isMinSignedValue())
2379 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2380 E->getType());
2381 return true;
2382 case BO_Shl: {
2383 if (Info.getLangOpts().OpenCL)
2384 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2385 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2386 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2387 RHS.isUnsigned());
2388 else if (RHS.isSigned() && RHS.isNegative()) {
2389 // During constant-folding, a negative shift is an opposite shift. Such
2390 // a shift is not a constant expression.
2391 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2392 RHS = -RHS;
2393 goto shift_right;
2394 }
2395 shift_left:
2396 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2397 // the shifted type.
2398 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2399 if (SA != RHS) {
2400 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2401 << RHS << E->getType() << LHS.getBitWidth();
2402 } else if (LHS.isSigned()) {
2403 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2404 // operand, and must not overflow the corresponding unsigned type.
2405 if (LHS.isNegative())
2406 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2407 else if (LHS.countLeadingZeros() < SA)
2408 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2409 }
2410 Result = LHS << SA;
2411 return true;
2412 }
2413 case BO_Shr: {
2414 if (Info.getLangOpts().OpenCL)
2415 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2416 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2417 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2418 RHS.isUnsigned());
2419 else if (RHS.isSigned() && RHS.isNegative()) {
2420 // During constant-folding, a negative shift is an opposite shift. Such a
2421 // shift is not a constant expression.
2422 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2423 RHS = -RHS;
2424 goto shift_left;
2425 }
2426 shift_right:
2427 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2428 // shifted type.
2429 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2430 if (SA != RHS)
2431 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2432 << RHS << E->getType() << LHS.getBitWidth();
2433 Result = LHS >> SA;
2434 return true;
2435 }
2436
2437 case BO_LT: Result = LHS < RHS; return true;
2438 case BO_GT: Result = LHS > RHS; return true;
2439 case BO_LE: Result = LHS <= RHS; return true;
2440 case BO_GE: Result = LHS >= RHS; return true;
2441 case BO_EQ: Result = LHS == RHS; return true;
2442 case BO_NE: Result = LHS != RHS; return true;
2443 case BO_Cmp:
2444 llvm_unreachable("BO_Cmp should be handled elsewhere");
2445 }
2446}
2447
2448/// Perform the given binary floating-point operation, in-place, on LHS.
2449static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2450 APFloat &LHS, BinaryOperatorKind Opcode,
2451 const APFloat &RHS) {
2452 switch (Opcode) {
2453 default:
2454 Info.FFDiag(E);
2455 return false;
2456 case BO_Mul:
2457 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2458 break;
2459 case BO_Add:
2460 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2461 break;
2462 case BO_Sub:
2463 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2464 break;
2465 case BO_Div:
2466 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2467 break;
2468 }
2469
2470 if (LHS.isInfinity() || LHS.isNaN()) {
2471 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2472 return Info.noteUndefinedBehavior();
2473 }
2474 return true;
2475}
2476
2477/// Cast an lvalue referring to a base subobject to a derived class, by
2478/// truncating the lvalue's path to the given length.
2479static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2480 const RecordDecl *TruncatedType,
2481 unsigned TruncatedElements) {
2482 SubobjectDesignator &D = Result.Designator;
2483
2484 // Check we actually point to a derived class object.
2485 if (TruncatedElements == D.Entries.size())
2486 return true;
2487 assert(TruncatedElements >= D.MostDerivedPathLength &&
2488 "not casting to a derived class");
2489 if (!Result.checkSubobject(Info, E, CSK_Derived))
2490 return false;
2491
2492 // Truncate the path to the subobject, and remove any derived-to-base offsets.
2493 const RecordDecl *RD = TruncatedType;
2494 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2495 if (RD->isInvalidDecl()) return false;
2496 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2497 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2498 if (isVirtualBaseClass(D.Entries[I]))
2499 Result.Offset -= Layout.getVBaseClassOffset(Base);
2500 else
2501 Result.Offset -= Layout.getBaseClassOffset(Base);
2502 RD = Base;
2503 }
2504 D.Entries.resize(TruncatedElements);
2505 return true;
2506}
2507
2508static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2509 const CXXRecordDecl *Derived,
2510 const CXXRecordDecl *Base,
2511 const ASTRecordLayout *RL = nullptr) {
2512 if (!RL) {
2513 if (Derived->isInvalidDecl()) return false;
2514 RL = &Info.Ctx.getASTRecordLayout(Derived);
2515 }
2516
2517 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2518 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2519 return true;
2520}
2521
2522static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2523 const CXXRecordDecl *DerivedDecl,
2524 const CXXBaseSpecifier *Base) {
2525 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2526
2527 if (!Base->isVirtual())
2528 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2529
2530 SubobjectDesignator &D = Obj.Designator;
2531 if (D.Invalid)
2532 return false;
2533
2534 // Extract most-derived object and corresponding type.
2535 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2536 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2537 return false;
2538
2539 // Find the virtual base class.
2540 if (DerivedDecl->isInvalidDecl()) return false;
2541 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2542 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2543 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2544 return true;
2545}
2546
2547static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2548 QualType Type, LValue &Result) {
2549 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2550 PathE = E->path_end();
2551 PathI != PathE; ++PathI) {
2552 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2553 *PathI))
2554 return false;
2555 Type = (*PathI)->getType();
2556 }
2557 return true;
2558}
2559
2560/// Cast an lvalue referring to a derived class to a known base subobject.
2561static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2562 const CXXRecordDecl *DerivedRD,
2563 const CXXRecordDecl *BaseRD) {
2564 CXXBasePaths Paths(/*FindAmbiguities=*/false,
2565 /*RecordPaths=*/true, /*DetectVirtual=*/false);
2566 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2567 llvm_unreachable("Class must be derived from the passed in base class!");
2568
2569 for (CXXBasePathElement &Elem : Paths.front())
2570 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2571 return false;
2572 return true;
2573}
2574
2575/// Update LVal to refer to the given field, which must be a member of the type
2576/// currently described by LVal.
2577static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2578 const FieldDecl *FD,
2579 const ASTRecordLayout *RL = nullptr) {
2580 if (!RL) {
2581 if (FD->getParent()->isInvalidDecl()) return false;
2582 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2583 }
2584
2585 unsigned I = FD->getFieldIndex();
2586 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2587 LVal.addDecl(Info, E, FD);
2588 return true;
2589}
2590
2591/// Update LVal to refer to the given indirect field.
2592static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2593 LValue &LVal,
2594 const IndirectFieldDecl *IFD) {
2595 for (const auto *C : IFD->chain())
2596 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2597 return false;
2598 return true;
2599}
2600
2601/// Get the size of the given type in char units.
2602static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2603 QualType Type, CharUnits &Size) {
2604 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2605 // extension.
2606 if (Type->isVoidType() || Type->isFunctionType()) {
2607 Size = CharUnits::One();
2608 return true;
2609 }
2610
2611 if (Type->isDependentType()) {
2612 Info.FFDiag(Loc);
2613 return false;
2614 }
2615
2616 if (!Type->isConstantSizeType()) {
2617 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2618 // FIXME: Better diagnostic.
2619 Info.FFDiag(Loc);
2620 return false;
2621 }
2622
2623 Size = Info.Ctx.getTypeSizeInChars(Type);
2624 return true;
2625}
2626
2627/// Update a pointer value to model pointer arithmetic.
2628/// \param Info - Information about the ongoing evaluation.
2629/// \param E - The expression being evaluated, for diagnostic purposes.
2630/// \param LVal - The pointer value to be updated.
2631/// \param EltTy - The pointee type represented by LVal.
2632/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2633static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2634 LValue &LVal, QualType EltTy,
2635 APSInt Adjustment) {
2636 CharUnits SizeOfPointee;
2637 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2638 return false;
2639
2640 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2641 return true;
2642}
2643
2644static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2645 LValue &LVal, QualType EltTy,
2646 int64_t Adjustment) {
2647 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2648 APSInt::get(Adjustment));
2649}
2650
2651/// Update an lvalue to refer to a component of a complex number.
2652/// \param Info - Information about the ongoing evaluation.
2653/// \param LVal - The lvalue to be updated.
2654/// \param EltTy - The complex number's component type.
2655/// \param Imag - False for the real component, true for the imaginary.
2656static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2657 LValue &LVal, QualType EltTy,
2658 bool Imag) {
2659 if (Imag) {
2660 CharUnits SizeOfComponent;
2661 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2662 return false;
2663 LVal.Offset += SizeOfComponent;
2664 }
2665 LVal.addComplex(Info, E, EltTy, Imag);
2666 return true;
2667}
2668
2669static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2670 QualType Type, const LValue &LVal,
2671 APValue &RVal);
2672
2673/// Try to evaluate the initializer for a variable declaration.
2674///
2675/// \param Info Information about the ongoing evaluation.
2676/// \param E An expression to be used when printing diagnostics.
2677/// \param VD The variable whose initializer should be obtained.
2678/// \param Frame The frame in which the variable was created. Must be null
2679/// if this variable is not local to the evaluation.
2680/// \param Result Filled in with a pointer to the value of the variable.
2681static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2682 const VarDecl *VD, CallStackFrame *Frame,
2683 APValue *&Result, const LValue *LVal) {
2684
2685 // If this is a parameter to an active constexpr function call, perform
2686 // argument substitution.
2687 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2688 // Assume arguments of a potential constant expression are unknown
2689 // constant expressions.
2690 if (Info.checkingPotentialConstantExpression())
2691 return false;
2692 if (!Frame || !Frame->Arguments) {
2693 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2694 return false;
2695 }
2696 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2697 return true;
2698 }
2699
2700 // If this is a local variable, dig out its value.
2701 if (Frame) {
2702 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2703 : Frame->getCurrentTemporary(VD);
2704 if (!Result) {
2705 // Assume variables referenced within a lambda's call operator that were
2706 // not declared within the call operator are captures and during checking
2707 // of a potential constant expression, assume they are unknown constant
2708 // expressions.
2709 assert(isLambdaCallOperator(Frame->Callee) &&
2710 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2711 "missing value for local variable");
2712 if (Info.checkingPotentialConstantExpression())
2713 return false;
2714 // FIXME: implement capture evaluation during constant expr evaluation.
2715 Info.FFDiag(E->getBeginLoc(),
2716 diag::note_unimplemented_constexpr_lambda_feature_ast)
2717 << "captures not currently allowed";
2718 return false;
2719 }
2720 return true;
2721 }
2722
2723 // Dig out the initializer, and use the declaration which it's attached to.
2724 const Expr *Init = VD->getAnyInitializer(VD);
2725 if (!Init || Init->isValueDependent()) {
2726 // If we're checking a potential constant expression, the variable could be
2727 // initialized later.
2728 if (!Info.checkingPotentialConstantExpression())
2729 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2730 return false;
2731 }
2732
2733 // If we're currently evaluating the initializer of this declaration, use that
2734 // in-flight value.
2735 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2736 Result = Info.EvaluatingDeclValue;
2737 return true;
2738 }
2739
2740 // Never evaluate the initializer of a weak variable. We can't be sure that
2741 // this is the definition which will be used.
2742 if (VD->isWeak()) {
2743 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2744 return false;
2745 }
2746
2747 // Check that we can fold the initializer. In C++, we will have already done
2748 // this in the cases where it matters for conformance.
2749 SmallVector<PartialDiagnosticAt, 8> Notes;
2750 if (!VD->evaluateValue(Notes)) {
2751 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2752 Notes.size() + 1) << VD;
2753 Info.Note(VD->getLocation(), diag::note_declared_at);
2754 Info.addNotes(Notes);
2755 return false;
2756 } else if (!VD->checkInitIsICE()) {
2757 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2758 Notes.size() + 1) << VD;
2759 Info.Note(VD->getLocation(), diag::note_declared_at);
2760 Info.addNotes(Notes);
2761 }
2762
2763 Result = VD->getEvaluatedValue();
2764 return true;
2765}
2766
2767static bool IsConstNonVolatile(QualType T) {
2768 Qualifiers Quals = T.getQualifiers();
2769 return Quals.hasConst() && !Quals.hasVolatile();
2770}
2771
2772/// Get the base index of the given base class within an APValue representing
2773/// the given derived class.
2774static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2775 const CXXRecordDecl *Base) {
2776 Base = Base->getCanonicalDecl();
2777 unsigned Index = 0;
2778 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2779 E = Derived->bases_end(); I != E; ++I, ++Index) {
2780 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2781 return Index;
2782 }
2783
2784 llvm_unreachable("base class missing from derived class's bases list");
2785}
2786
2787/// Extract the value of a character from a string literal.
2788static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2789 uint64_t Index) {
2790 assert(!isa<SourceLocExpr>(Lit) &&
2791 "SourceLocExpr should have already been converted to a StringLiteral");
2792
2793 // FIXME: Support MakeStringConstant
2794 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2795 std::string Str;
2796 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2797 assert(Index <= Str.size() && "Index too large");
2798 return APSInt::getUnsigned(Str.c_str()[Index]);
2799 }
2800
2801 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2802 Lit = PE->getFunctionName();
2803 const StringLiteral *S = cast<StringLiteral>(Lit);
2804 const ConstantArrayType *CAT =
2805 Info.Ctx.getAsConstantArrayType(S->getType());
2806 assert(CAT && "string literal isn't an array");
2807 QualType CharType = CAT->getElementType();
2808 assert(CharType->isIntegerType() && "unexpected character type");
2809
2810 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2811 CharType->isUnsignedIntegerType());
2812 if (Index < S->getLength())
2813 Value = S->getCodeUnit(Index);
2814 return Value;
2815}
2816
2817// Expand a string literal into an array of characters.
2818//
2819// FIXME: This is inefficient; we should probably introduce something similar
2820// to the LLVM ConstantDataArray to make this cheaper.
2821static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
2822 APValue &Result) {
2823 const ConstantArrayType *CAT =
2824 Info.Ctx.getAsConstantArrayType(S->getType());
2825 assert(CAT && "string literal isn't an array");
2826 QualType CharType = CAT->getElementType();
2827 assert(CharType->isIntegerType() && "unexpected character type");
2828
2829 unsigned Elts = CAT->getSize().getZExtValue();
2830 Result = APValue(APValue::UninitArray(),
2831 std::min(S->getLength(), Elts), Elts);
2832 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2833 CharType->isUnsignedIntegerType());
2834 if (Result.hasArrayFiller())
2835 Result.getArrayFiller() = APValue(Value);
2836 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2837 Value = S->getCodeUnit(I);
2838 Result.getArrayInitializedElt(I) = APValue(Value);
2839 }
2840}
2841
2842// Expand an array so that it has more than Index filled elements.
2843static void expandArray(APValue &Array, unsigned Index) {
2844 unsigned Size = Array.getArraySize();
2845 assert(Index < Size);
2846
2847 // Always at least double the number of elements for which we store a value.
2848 unsigned OldElts = Array.getArrayInitializedElts();
2849 unsigned NewElts = std::max(Index+1, OldElts * 2);
2850 NewElts = std::min(Size, std::max(NewElts, 8u));
2851
2852 // Copy the data across.
2853 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2854 for (unsigned I = 0; I != OldElts; ++I)
2855 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2856 for (unsigned I = OldElts; I != NewElts; ++I)
2857 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2858 if (NewValue.hasArrayFiller())
2859 NewValue.getArrayFiller() = Array.getArrayFiller();
2860 Array.swap(NewValue);
2861}
2862
2863/// Determine whether a type would actually be read by an lvalue-to-rvalue
2864/// conversion. If it's of class type, we may assume that the copy operation
2865/// is trivial. Note that this is never true for a union type with fields
2866/// (because the copy always "reads" the active member) and always true for
2867/// a non-class type.
2868static bool isReadByLvalueToRvalueConversion(QualType T) {
2869 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2870 if (!RD || (RD->isUnion() && !RD->field_empty()))
2871 return true;
2872 if (RD->isEmpty())
2873 return false;
2874
2875 for (auto *Field : RD->fields())
2876 if (isReadByLvalueToRvalueConversion(Field->getType()))
2877 return true;
2878
2879 for (auto &BaseSpec : RD->bases())
2880 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2881 return true;
2882
2883 return false;
2884}
2885
2886/// Diagnose an attempt to read from any unreadable field within the specified
2887/// type, which might be a class type.
2888static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2889 QualType T) {
2890 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2891 if (!RD)
2892 return false;
2893
2894 if (!RD->hasMutableFields())
2895 return false;
2896
2897 for (auto *Field : RD->fields()) {
2898 // If we're actually going to read this field in some way, then it can't
2899 // be mutable. If we're in a union, then assigning to a mutable field
2900 // (even an empty one) can change the active member, so that's not OK.
2901 // FIXME: Add core issue number for the union case.
2902 if (Field->isMutable() &&
2903 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2904 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2905 Info.Note(Field->getLocation(), diag::note_declared_at);
2906 return true;
2907 }
2908
2909 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2910 return true;
2911 }
2912
2913 for (auto &BaseSpec : RD->bases())
2914 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2915 return true;
2916
2917 // All mutable fields were empty, and thus not actually read.
2918 return false;
2919}
2920
2921static bool lifetimeStartedInEvaluation(EvalInfo &Info,
2922 APValue::LValueBase Base) {
2923 // A temporary we created.
2924 if (Base.getCallIndex())
2925 return true;
2926
2927 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2928 if (!Evaluating)
2929 return false;
2930
2931 // The variable whose initializer we're evaluating.
2932 if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
2933 if (declaresSameEntity(Evaluating, BaseD))
2934 return true;
2935
2936 // A temporary lifetime-extended by the variable whose initializer we're
2937 // evaluating.
2938 if (auto *BaseE = Base.dyn_cast<const Expr *>())
2939 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
2940 if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
2941 return true;
2942
2943 return false;
2944}
2945
2946namespace {
2947/// A handle to a complete object (an object that is not a subobject of
2948/// another object).
2949struct CompleteObject {
2950 /// The identity of the object.
2951 APValue::LValueBase Base;
2952 /// The value of the complete object.
2953 APValue *Value;
2954 /// The type of the complete object.
2955 QualType Type;
2956
2957 CompleteObject() : Value(nullptr) {}
2958 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
2959 : Base(Base), Value(Value), Type(Type) {}
2960
2961 bool mayReadMutableMembers(EvalInfo &Info) const {
2962 // In C++14 onwards, it is permitted to read a mutable member whose
2963 // lifetime began within the evaluation.
2964 // FIXME: Should we also allow this in C++11?
2965 if (!Info.getLangOpts().CPlusPlus14)
2966 return false;
2967 return lifetimeStartedInEvaluation(Info, Base);
2968 }
2969
2970 explicit operator bool() const { return !Type.isNull(); }
2971};
2972} // end anonymous namespace
2973
2974static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
2975 bool IsMutable = false) {
2976 // C++ [basic.type.qualifier]p1:
2977 // - A const object is an object of type const T or a non-mutable subobject
2978 // of a const object.
2979 if (ObjType.isConstQualified() && !IsMutable)
2980 SubobjType.addConst();
2981 // - A volatile object is an object of type const T or a subobject of a
2982 // volatile object.
2983 if (ObjType.isVolatileQualified())
2984 SubobjType.addVolatile();
2985 return SubobjType;
2986}
2987
2988/// Find the designated sub-object of an rvalue.
2989template<typename SubobjectHandler>
2990typename SubobjectHandler::result_type
2991findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2992 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2993 if (Sub.Invalid)
2994 // A diagnostic will have already been produced.
2995 return handler.failed();
2996 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2997 if (Info.getLangOpts().CPlusPlus11)
2998 Info.FFDiag(E, Sub.isOnePastTheEnd()
2999 ? diag::note_constexpr_access_past_end
3000 : diag::note_constexpr_access_unsized_array)
3001 << handler.AccessKind;
3002 else
3003 Info.FFDiag(E);
3004 return handler.failed();
3005 }
3006
3007 APValue *O = Obj.Value;
3008 QualType ObjType = Obj.Type;
3009 const FieldDecl *LastField = nullptr;
3010 const FieldDecl *VolatileField = nullptr;
3011
3012 // Walk the designator's path to find the subobject.
3013 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3014 // Reading an indeterminate value is undefined, but assigning over one is OK.
3015 if (O->isAbsent() || (O->isIndeterminate() && handler.AccessKind != AK_Assign)) {
3016 if (!Info.checkingPotentialConstantExpression())
3017 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3018 << handler.AccessKind << O->isIndeterminate();
3019 return handler.failed();
3020 }
3021
3022 // C++ [class.ctor]p5:
3023 // const and volatile semantics are not applied on an object under
3024 // construction.
3025 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3026 ObjType->isRecordType() &&
3027 Info.isEvaluatingConstructor(
3028 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3029 Sub.Entries.begin() + I)) !=
3030 ConstructionPhase::None) {
3031 ObjType = Info.Ctx.getCanonicalType(ObjType);
3032 ObjType.removeLocalConst();
3033 ObjType.removeLocalVolatile();
3034 }
3035
3036 // If this is our last pass, check that the final object type is OK.
3037 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3038 // Accesses to volatile objects are prohibited.
3039 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3040 if (Info.getLangOpts().CPlusPlus) {
3041 int DiagKind;
3042 SourceLocation Loc;
3043 const NamedDecl *Decl = nullptr;
3044 if (VolatileField) {
3045 DiagKind = 2;
3046 Loc = VolatileField->getLocation();
3047 Decl = VolatileField;
3048 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3049 DiagKind = 1;
3050 Loc = VD->getLocation();
3051 Decl = VD;
3052 } else {
3053 DiagKind = 0;
3054 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3055 Loc = E->getExprLoc();
3056 }
3057 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3058 << handler.AccessKind << DiagKind << Decl;
3059 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3060 } else {
3061 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3062 }
3063 return handler.failed();
3064 }
3065
3066 // If we are reading an object of class type, there may still be more
3067 // things we need to check: if there are any mutable subobjects, we
3068 // cannot perform this read. (This only happens when performing a trivial
3069 // copy or assignment.)
3070 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
3071 !Obj.mayReadMutableMembers(Info) &&
3072 diagnoseUnreadableFields(Info, E, ObjType))
3073 return handler.failed();
3074 }
3075
3076 if (I == N) {
3077 if (!handler.found(*O, ObjType))
3078 return false;
3079
3080 // If we modified a bit-field, truncate it to the right width.
3081 if (isModification(handler.AccessKind) &&
3082 LastField && LastField->isBitField() &&
3083 !truncateBitfieldValue(Info, E, *O, LastField))
3084 return false;
3085
3086 return true;
3087 }
3088
3089 LastField = nullptr;
3090 if (ObjType->isArrayType()) {
3091 // Next subobject is an array element.
3092 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3093 assert(CAT && "vla in literal type?");
3094 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3095 if (CAT->getSize().ule(Index)) {
3096 // Note, it should not be possible to form a pointer with a valid
3097 // designator which points more than one past the end of the array.
3098 if (Info.getLangOpts().CPlusPlus11)
3099 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3100 << handler.AccessKind;
3101 else
3102 Info.FFDiag(E);
3103 return handler.failed();
3104 }
3105
3106 ObjType = CAT->getElementType();
3107
3108 if (O->getArrayInitializedElts() > Index)
3109 O = &O->getArrayInitializedElt(Index);
3110 else if (handler.AccessKind != AK_Read) {
3111 expandArray(*O, Index);
3112 O = &O->getArrayInitializedElt(Index);
3113 } else
3114 O = &O->getArrayFiller();
3115 } else if (ObjType->isAnyComplexType()) {
3116 // Next subobject is a complex number.
3117 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3118 if (Index > 1) {
3119 if (Info.getLangOpts().CPlusPlus11)
3120 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3121 << handler.AccessKind;
3122 else
3123 Info.FFDiag(E);
3124 return handler.failed();
3125 }
3126
3127 ObjType = getSubobjectType(
3128 ObjType, ObjType->castAs<ComplexType>()->getElementType());
3129
3130 assert(I == N - 1 && "extracting subobject of scalar?");
3131 if (O->isComplexInt()) {
3132 return handler.found(Index ? O->getComplexIntImag()
3133 : O->getComplexIntReal(), ObjType);
3134 } else {
3135 assert(O->isComplexFloat());
3136 return handler.found(Index ? O->getComplexFloatImag()
3137 : O->getComplexFloatReal(), ObjType);
3138 }
3139 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3140 if (Field->isMutable() && handler.AccessKind == AK_Read &&
3141 !Obj.mayReadMutableMembers(Info)) {
3142 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
3143 << Field;
3144 Info.Note(Field->getLocation(), diag::note_declared_at);
3145 return handler.failed();
3146 }
3147
3148 // Next subobject is a class, struct or union field.
3149 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3150 if (RD->isUnion()) {
3151 const FieldDecl *UnionField = O->getUnionField();
3152 if (!UnionField ||
3153 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3154 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3155 << handler.AccessKind << Field << !UnionField << UnionField;
3156 return handler.failed();
3157 }
3158 O = &O->getUnionValue();
3159 } else
3160 O = &O->getStructField(Field->getFieldIndex());
3161
3162 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3163 LastField = Field;
3164 if (Field->getType().isVolatileQualified())
3165 VolatileField = Field;
3166 } else {
3167 // Next subobject is a base class.
3168 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3169 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3170 O = &O->getStructBase(getBaseIndex(Derived, Base));
3171
3172 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3173 }
3174 }
3175}
3176
3177namespace {
3178struct ExtractSubobjectHandler {
3179 EvalInfo &Info;
3180 APValue &Result;
3181
3182 static const AccessKinds AccessKind = AK_Read;
3183
3184 typedef bool result_type;
3185 bool failed() { return false; }
3186 bool found(APValue &Subobj, QualType SubobjType) {
3187 Result = Subobj;
3188 return true;
3189 }
3190 bool found(APSInt &Value, QualType SubobjType) {
3191 Result = APValue(Value);
3192 return true;
3193 }
3194 bool found(APFloat &Value, QualType SubobjType) {
3195 Result = APValue(Value);
3196 return true;
3197 }
3198};
3199} // end anonymous namespace
3200
3201const AccessKinds ExtractSubobjectHandler::AccessKind;
3202
3203/// Extract the designated sub-object of an rvalue.
3204static bool extractSubobject(EvalInfo &Info, const Expr *E,
3205 const CompleteObject &Obj,
3206 const SubobjectDesignator &Sub,
3207 APValue &Result) {
3208 ExtractSubobjectHandler Handler = { Info, Result };
3209 return findSubobject(Info, E, Obj, Sub, Handler);
3210}
3211
3212namespace {
3213struct ModifySubobjectHandler {
3214 EvalInfo &Info;
3215 APValue &NewVal;
3216 const Expr *E;
3217
3218 typedef bool result_type;
3219 static const AccessKinds AccessKind = AK_Assign;
3220
3221 bool checkConst(QualType QT) {
3222 // Assigning to a const object has undefined behavior.
3223 if (QT.isConstQualified()) {
3224 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3225 return false;
3226 }
3227 return true;
3228 }
3229
3230 bool failed() { return false; }
3231 bool found(APValue &Subobj, QualType SubobjType) {
3232 if (!checkConst(SubobjType))
3233 return false;
3234 // We've been given ownership of NewVal, so just swap it in.
3235 Subobj.swap(NewVal);
3236 return true;
3237 }
3238 bool found(APSInt &Value, QualType SubobjType) {
3239 if (!checkConst(SubobjType))
3240 return false;
3241 if (!NewVal.isInt()) {
3242 // Maybe trying to write a cast pointer value into a complex?
3243 Info.FFDiag(E);
3244 return false;
3245 }
3246 Value = NewVal.getInt();
3247 return true;
3248 }
3249 bool found(APFloat &Value, QualType SubobjType) {
3250 if (!checkConst(SubobjType))
3251 return false;
3252 Value = NewVal.getFloat();
3253 return true;
3254 }
3255};
3256} // end anonymous namespace
3257
3258const AccessKinds ModifySubobjectHandler::AccessKind;
3259
3260/// Update the designated sub-object of an rvalue to the given value.
3261static bool modifySubobject(EvalInfo &Info, const Expr *E,
3262 const CompleteObject &Obj,
3263 const SubobjectDesignator &Sub,
3264 APValue &NewVal) {
3265 ModifySubobjectHandler Handler = { Info, NewVal, E };
3266 return findSubobject(Info, E, Obj, Sub, Handler);
3267}
3268
3269/// Find the position where two subobject designators diverge, or equivalently
3270/// the length of the common initial subsequence.
3271static unsigned FindDesignatorMismatch(QualType ObjType,
3272 const SubobjectDesignator &A,
3273 const SubobjectDesignator &B,
3274 bool &WasArrayIndex) {
3275 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3276 for (/**/; I != N; ++I) {
3277 if (!ObjType.isNull() &&
3278 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3279 // Next subobject is an array element.
3280 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3281 WasArrayIndex = true;
3282 return I;
3283 }
3284 if (ObjType->isAnyComplexType())
3285 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3286 else
3287 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3288 } else {
3289 if (A.Entries[I].getAsBaseOrMember() !=
3290 B.Entries[I].getAsBaseOrMember()) {
3291 WasArrayIndex = false;
3292 return I;
3293 }
3294 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3295 // Next subobject is a field.
3296 ObjType = FD->getType();
3297 else
3298 // Next subobject is a base class.
3299 ObjType = QualType();
3300 }
3301 }
3302 WasArrayIndex = false;
3303 return I;
3304}
3305
3306/// Determine whether the given subobject designators refer to elements of the
3307/// same array object.
3308static bool AreElementsOfSameArray(QualType ObjType,
3309 const SubobjectDesignator &A,
3310 const SubobjectDesignator &B) {
3311 if (A.Entries.size() != B.Entries.size())
3312 return false;
3313
3314 bool IsArray = A.MostDerivedIsArrayElement;
3315 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3316 // A is a subobject of the array element.
3317 return false;
3318
3319 // If A (and B) designates an array element, the last entry will be the array
3320 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3321 // of length 1' case, and the entire path must match.
3322 bool WasArrayIndex;
3323 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3324 return CommonLength >= A.Entries.size() - IsArray;
3325}
3326
3327/// Find the complete object to which an LValue refers.
3328static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3329 AccessKinds AK, const LValue &LVal,
3330 QualType LValType) {
3331 if (LVal.InvalidBase) {
3332 Info.FFDiag(E);
3333 return CompleteObject();
3334 }
3335
3336 if (!LVal.Base) {
3337 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3338 return CompleteObject();
3339 }
3340
3341 CallStackFrame *Frame = nullptr;
3342 unsigned Depth = 0;
3343 if (LVal.getLValueCallIndex()) {
3344 std::tie(Frame, Depth) =
3345 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3346 if (!Frame) {
3347 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3348 << AK << LVal.Base.is<const ValueDecl*>();
3349 NoteLValueLocation(Info, LVal.Base);
3350 return CompleteObject();
3351 }
3352 }
3353
3354 bool IsAccess = isFormalAccess(AK);
3355
3356 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3357 // is not a constant expression (even if the object is non-volatile). We also
3358 // apply this rule to C++98, in order to conform to the expected 'volatile'
3359 // semantics.
3360 if (IsAccess && LValType.isVolatileQualified()) {
3361 if (Info.getLangOpts().CPlusPlus)
3362 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3363 << AK << LValType;
3364 else
3365 Info.FFDiag(E);
3366 return CompleteObject();
3367 }
3368
3369 // Compute value storage location and type of base object.
3370 APValue *BaseVal = nullptr;
3371 QualType BaseType = getType(LVal.Base);
3372
3373 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3374 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3375 // In C++11, constexpr, non-volatile variables initialized with constant
3376 // expressions are constant expressions too. Inside constexpr functions,
3377 // parameters are constant expressions even if they're non-const.
3378 // In C++1y, objects local to a constant expression (those with a Frame) are
3379 // both readable and writable inside constant expressions.
3380 // In C, such things can also be folded, although they are not ICEs.
3381 const VarDecl *VD = dyn_cast<VarDecl>(D);
3382 if (VD) {
3383 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3384 VD = VDef;
3385 }
3386 if (!VD || VD->isInvalidDecl()) {
3387 Info.FFDiag(E);
3388 return CompleteObject();
3389 }
3390
3391 // Unless we're looking at a local variable or argument in a constexpr call,
3392 // the variable we're reading must be const.
3393 if (!Frame) {
3394 if (Info.getLangOpts().CPlusPlus14 &&
3395 declaresSameEntity(
3396 VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
3397 // OK, we can read and modify an object if we're in the process of
3398 // evaluating its initializer, because its lifetime began in this
3399 // evaluation.
3400 } else if (isModification(AK)) {
3401 // All the remaining cases do not permit modification of the object.
3402 Info.FFDiag(E, diag::note_constexpr_modify_global);
3403 return CompleteObject();
3404 } else if (VD->isConstexpr()) {
3405 // OK, we can read this variable.
3406 } else if (BaseType->isIntegralOrEnumerationType()) {
3407 // In OpenCL if a variable is in constant address space it is a const
3408 // value.
3409 if (!(BaseType.isConstQualified() ||
3410 (Info.getLangOpts().OpenCL &&
3411 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3412 if (!IsAccess)
3413 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3414 if (Info.getLangOpts().CPlusPlus) {
3415 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3416 Info.Note(VD->getLocation(), diag::note_declared_at);
3417 } else {
3418 Info.FFDiag(E);
3419 }
3420 return CompleteObject();
3421 }
3422 } else if (!IsAccess) {
3423 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3424 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3425 // We support folding of const floating-point types, in order to make
3426 // static const data members of such types (supported as an extension)
3427 // more useful.
3428 if (Info.getLangOpts().CPlusPlus11) {
3429 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3430 Info.Note(VD->getLocation(), diag::note_declared_at);
3431 } else {
3432 Info.CCEDiag(E);
3433 }
3434 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3435 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3436 // Keep evaluating to see what we can do.
3437 } else {
3438 // FIXME: Allow folding of values of any literal type in all languages.
3439 if (Info.checkingPotentialConstantExpression() &&
3440 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3441 // The definition of this variable could be constexpr. We can't
3442 // access it right now, but may be able to in future.
3443 } else if (Info.getLangOpts().CPlusPlus11) {
3444 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3445 Info.Note(VD->getLocation(), diag::note_declared_at);
3446 } else {
3447 Info.FFDiag(E);
3448 }
3449 return CompleteObject();
3450 }
3451 }
3452
3453 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3454 return CompleteObject();
3455 } else {
3456 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3457
3458 if (!Frame) {
3459 if (const MaterializeTemporaryExpr *MTE =
3460 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3461 assert(MTE->getStorageDuration() == SD_Static &&
3462 "should have a frame for a non-global materialized temporary");
3463
3464 // Per C++1y [expr.const]p2:
3465 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3466 // - a [...] glvalue of integral or enumeration type that refers to
3467 // a non-volatile const object [...]
3468 // [...]
3469 // - a [...] glvalue of literal type that refers to a non-volatile
3470 // object whose lifetime began within the evaluation of e.
3471 //
3472 // C++11 misses the 'began within the evaluation of e' check and
3473 // instead allows all temporaries, including things like:
3474 // int &&r = 1;
3475 // int x = ++r;
3476 // constexpr int k = r;
3477 // Therefore we use the C++14 rules in C++11 too.
3478 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3479 const ValueDecl *ED = MTE->getExtendingDecl();
3480 if (!(BaseType.isConstQualified() &&
3481 BaseType->isIntegralOrEnumerationType()) &&
3482 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3483 if (!IsAccess)
3484 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3485 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3486 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3487 return CompleteObject();
3488 }
3489
3490 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3491 assert(BaseVal && "got reference to unevaluated temporary");
3492 } else {
3493 if (!IsAccess)
3494 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3495 APValue Val;
3496 LVal.moveInto(Val);
3497 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3498 << AK
3499 << Val.getAsString(Info.Ctx,
3500 Info.Ctx.getLValueReferenceType(LValType));
3501 NoteLValueLocation(Info, LVal.Base);
3502 return CompleteObject();
3503 }
3504 } else {
3505 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3506 assert(BaseVal && "missing value for temporary");
3507 }
3508 }
3509
3510 // In C++14, we can't safely access any mutable state when we might be
3511 // evaluating after an unmodeled side effect.
3512 //
3513 // FIXME: Not all local state is mutable. Allow local constant subobjects
3514 // to be read here (but take care with 'mutable' fields).
3515 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3516 Info.EvalStatus.HasSideEffects) ||
3517 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
3518 return CompleteObject();
3519
3520 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
3521}
3522
3523/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3524/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3525/// glvalue referred to by an entity of reference type.
3526///
3527/// \param Info - Information about the ongoing evaluation.
3528/// \param Conv - The expression for which we are performing the conversion.
3529/// Used for diagnostics.
3530/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3531/// case of a non-class type).
3532/// \param LVal - The glvalue on which we are attempting to perform this action.
3533/// \param RVal - The produced value will be placed here.
3534static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3535 QualType Type,
3536 const LValue &LVal, APValue &RVal) {
3537 if (LVal.Designator.Invalid)
3538 return false;
3539
3540 // Check for special cases where there is no existing APValue to look at.
3541 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3542
3543 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3544 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3545 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3546 // initializer until now for such expressions. Such an expression can't be
3547 // an ICE in C, so this only matters for fold.
3548 if (Type.isVolatileQualified()) {
3549 Info.FFDiag(Conv);
3550 return false;
3551 }
3552 APValue Lit;
3553 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3554 return false;
3555 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
3556 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3557 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3558 // Special-case character extraction so we don't have to construct an
3559 // APValue for the whole string.
3560 assert(LVal.Designator.Entries.size() <= 1 &&
3561 "Can only read characters from string literals");
3562 if (LVal.Designator.Entries.empty()) {
3563 // Fail for now for LValue to RValue conversion of an array.
3564 // (This shouldn't show up in C/C++, but it could be triggered by a
3565 // weird EvaluateAsRValue call from a tool.)
3566 Info.FFDiag(Conv);
3567 return false;
3568 }
3569 if (LVal.Designator.isOnePastTheEnd()) {
3570 if (Info.getLangOpts().CPlusPlus11)
3571 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read;
3572 else
3573 Info.FFDiag(Conv);
3574 return false;
3575 }
3576 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
3577 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3578 return true;
3579 }
3580 }
3581
3582 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3583 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3584}
3585
3586/// Perform an assignment of Val to LVal. Takes ownership of Val.
3587static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3588 QualType LValType, APValue &Val) {
3589 if (LVal.Designator.Invalid)
3590 return false;
3591
3592 if (!Info.getLangOpts().CPlusPlus14) {
3593 Info.FFDiag(E);
3594 return false;
3595 }
3596
3597 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3598 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3599}
3600
3601namespace {
3602struct CompoundAssignSubobjectHandler {
3603 EvalInfo &Info;
3604 const Expr *E;
3605 QualType PromotedLHSType;
3606 BinaryOperatorKind Opcode;
3607 const APValue &RHS;
3608
3609 static const AccessKinds AccessKind = AK_Assign;
3610
3611 typedef bool result_type;
3612
3613 bool checkConst(QualType QT) {
3614 // Assigning to a const object has undefined behavior.
3615 if (QT.isConstQualified()) {
3616 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3617 return false;
3618 }
3619 return true;
3620 }
3621
3622 bool failed() { return false; }
3623 bool found(APValue &Subobj, QualType SubobjType) {
3624 switch (Subobj.getKind()) {
3625 case APValue::Int:
3626 return found(Subobj.getInt(), SubobjType);
3627 case APValue::Float:
3628 return found(Subobj.getFloat(), SubobjType);
3629 case APValue::ComplexInt:
3630 case APValue::ComplexFloat:
3631 // FIXME: Implement complex compound assignment.
3632 Info.FFDiag(E);
3633 return false;
3634 case APValue::LValue:
3635 return foundPointer(Subobj, SubobjType);
3636 default:
3637 // FIXME: can this happen?
3638 Info.FFDiag(E);
3639 return false;
3640 }
3641 }
3642 bool found(APSInt &Value, QualType SubobjType) {
3643 if (!checkConst(SubobjType))
3644 return false;
3645
3646 if (!SubobjType->isIntegerType()) {
3647 // We don't support compound assignment on integer-cast-to-pointer
3648 // values.
3649 Info.FFDiag(E);
3650 return false;
3651 }
3652
3653 if (RHS.isInt()) {
3654 APSInt LHS =
3655 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3656 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3657 return false;
3658 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3659 return true;
3660 } else if (RHS.isFloat()) {
3661 APFloat FValue(0.0);
3662 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3663 FValue) &&
3664 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3665 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3666 Value);
3667 }
3668
3669 Info.FFDiag(E);
3670 return false;
3671 }
3672 bool found(APFloat &Value, QualType SubobjType) {
3673 return checkConst(SubobjType) &&
3674 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3675 Value) &&
3676 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3677 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3678 }
3679 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3680 if (!checkConst(SubobjType))
3681 return false;
3682
3683 QualType PointeeType;
3684 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3685 PointeeType = PT->getPointeeType();
3686
3687 if (PointeeType.isNull() || !RHS.isInt() ||
3688 (Opcode != BO_Add && Opcode != BO_Sub)) {
3689 Info.FFDiag(E);
3690 return false;
3691 }
3692
3693 APSInt Offset = RHS.getInt();
3694 if (Opcode == BO_Sub)
3695 negateAsSigned(Offset);
3696
3697 LValue LVal;
3698 LVal.setFrom(Info.Ctx, Subobj);
3699 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3700 return false;
3701 LVal.moveInto(Subobj);
3702 return true;
3703 }
3704};
3705} // end anonymous namespace
3706
3707const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3708
3709/// Perform a compound assignment of LVal <op>= RVal.
3710static bool handleCompoundAssignment(
3711 EvalInfo &Info, const Expr *E,
3712 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3713 BinaryOperatorKind Opcode, const APValue &RVal) {
3714 if (LVal.Designator.Invalid)
3715 return false;
3716
3717 if (!Info.getLangOpts().CPlusPlus14) {
3718 Info.FFDiag(E);
3719 return false;
3720 }
3721
3722 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3723 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3724 RVal };
3725 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3726}
3727
3728namespace {
3729struct IncDecSubobjectHandler {
3730 EvalInfo &Info;
3731 const UnaryOperator *E;
3732 AccessKinds AccessKind;
3733 APValue *Old;
3734
3735 typedef bool result_type;
3736
3737 bool checkConst(QualType QT) {
3738 // Assigning to a const object has undefined behavior.
3739 if (QT.isConstQualified()) {
3740 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3741 return false;
3742 }
3743 return true;
3744 }
3745
3746 bool failed() { return false; }
3747 bool found(APValue &Subobj, QualType SubobjType) {
3748 // Stash the old value. Also clear Old, so we don't clobber it later
3749 // if we're post-incrementing a complex.
3750 if (Old) {
3751 *Old = Subobj;
3752 Old = nullptr;
3753 }
3754
3755 switch (Subobj.getKind()) {
3756 case APValue::Int:
3757 return found(Subobj.getInt(), SubobjType);
3758 case APValue::Float:
3759 return found(Subobj.getFloat(), SubobjType);
3760 case APValue::ComplexInt:
3761 return found(Subobj.getComplexIntReal(),
3762 SubobjType->castAs<ComplexType>()->getElementType()
3763 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3764 case APValue::ComplexFloat:
3765 return found(Subobj.getComplexFloatReal(),
3766 SubobjType->castAs<ComplexType>()->getElementType()
3767 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3768 case APValue::LValue:
3769 return foundPointer(Subobj, SubobjType);
3770 default:
3771 // FIXME: can this happen?
3772 Info.FFDiag(E);
3773 return false;
3774 }
3775 }
3776 bool found(APSInt &Value, QualType SubobjType) {
3777 if (!checkConst(SubobjType))
3778 return false;
3779
3780 if (!SubobjType->isIntegerType()) {
3781 // We don't support increment / decrement on integer-cast-to-pointer
3782 // values.
3783 Info.FFDiag(E);
3784 return false;
3785 }
3786
3787 if (Old) *Old = APValue(Value);
3788
3789 // bool arithmetic promotes to int, and the conversion back to bool
3790 // doesn't reduce mod 2^n, so special-case it.
3791 if (SubobjType->isBooleanType()) {
3792 if (AccessKind == AK_Increment)
3793 Value = 1;
3794 else
3795 Value = !Value;
3796 return true;
3797 }
3798
3799 bool WasNegative = Value.isNegative();
3800 if (AccessKind == AK_Increment) {
3801 ++Value;
3802
3803 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3804 APSInt ActualValue(Value, /*IsUnsigned*/true);
3805 return HandleOverflow(Info, E, ActualValue, SubobjType);
3806 }
3807 } else {
3808 --Value;
3809
3810 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3811 unsigned BitWidth = Value.getBitWidth();
3812 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3813 ActualValue.setBit(BitWidth);
3814 return HandleOverflow(Info, E, ActualValue, SubobjType);
3815 }
3816 }
3817 return true;
3818 }
3819 bool found(APFloat &Value, QualType SubobjType) {
3820 if (!checkConst(SubobjType))
3821 return false;
3822
3823 if (Old) *Old = APValue(Value);
3824
3825 APFloat One(Value.getSemantics(), 1);
3826 if (AccessKind == AK_Increment)
3827 Value.add(One, APFloat::rmNearestTiesToEven);
3828 else
3829 Value.subtract(One, APFloat::rmNearestTiesToEven);
3830 return true;
3831 }
3832 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3833 if (!checkConst(SubobjType))
3834 return false;
3835
3836 QualType PointeeType;
3837 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3838 PointeeType = PT->getPointeeType();
3839 else {
3840 Info.FFDiag(E);
3841 return false;
3842 }
3843
3844 LValue LVal;
3845 LVal.setFrom(Info.Ctx, Subobj);
3846 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3847 AccessKind == AK_Increment ? 1 : -1))
3848 return false;
3849 LVal.moveInto(Subobj);
3850 return true;
3851 }
3852};
3853} // end anonymous namespace
3854
3855/// Perform an increment or decrement on LVal.
3856static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3857 QualType LValType, bool IsIncrement, APValue *Old) {
3858 if (LVal.Designator.Invalid)
3859 return false;
3860
3861 if (!Info.getLangOpts().CPlusPlus14) {
3862 Info.FFDiag(E);
3863 return false;
3864 }
3865
3866 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3867 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3868 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3869 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3870}
3871
3872/// Build an lvalue for the object argument of a member function call.
3873static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3874 LValue &This) {
3875 if (Object->getType()->isPointerType())
3876 return EvaluatePointer(Object, This, Info);
3877
3878 if (Object->isGLValue())
3879 return EvaluateLValue(Object, This, Info);
3880
3881 if (Object->getType()->isLiteralType(Info.Ctx))
3882 return EvaluateTemporary(Object, This, Info);
3883
3884 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3885 return false;
3886}
3887
3888/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3889/// lvalue referring to the result.
3890///
3891/// \param Info - Information about the ongoing evaluation.
3892/// \param LV - An lvalue referring to the base of the member pointer.
3893/// \param RHS - The member pointer expression.
3894/// \param IncludeMember - Specifies whether the member itself is included in
3895/// the resulting LValue subobject designator. This is not possible when
3896/// creating a bound member function.
3897/// \return The field or method declaration to which the member pointer refers,
3898/// or 0 if evaluation fails.
3899static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3900 QualType LVType,
3901 LValue &LV,
3902 const Expr *RHS,
3903 bool IncludeMember = true) {
3904 MemberPtr MemPtr;
3905 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3906 return nullptr;
3907
3908 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3909 // member value, the behavior is undefined.
3910 if (!MemPtr.getDecl()) {
3911 // FIXME: Specific diagnostic.
3912 Info.FFDiag(RHS);
3913 return nullptr;
3914 }
3915
3916 if (MemPtr.isDerivedMember()) {
3917 // This is a member of some derived class. Truncate LV appropriately.
3918 // The end of the derived-to-base path for the base object must match the
3919 // derived-to-base path for the member pointer.
3920 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3921 LV.Designator.Entries.size()) {
3922 Info.FFDiag(RHS);
3923 return nullptr;
3924 }
3925 unsigned PathLengthToMember =
3926 LV.Designator.Entries.size() - MemPtr.Path.size();
3927 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3928 const CXXRecordDecl *LVDecl = getAsBaseClass(
3929 LV.Designator.Entries[PathLengthToMember + I]);
3930 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3931 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3932 Info.FFDiag(RHS);
3933 return nullptr;
3934 }
3935 }
3936
3937 // Truncate the lvalue to the appropriate derived class.
3938 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3939 PathLengthToMember))
3940 return nullptr;
3941 } else if (!MemPtr.Path.empty()) {
3942 // Extend the LValue path with the member pointer's path.
3943 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3944 MemPtr.Path.size() + IncludeMember);
3945
3946 // Walk down to the appropriate base class.
3947 if (const PointerType *PT = LVType->getAs<PointerType>())
3948 LVType = PT->getPointeeType();
3949 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3950 assert(RD && "member pointer access on non-class-type expression");
3951 // The first class in the path is that of the lvalue.
3952 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3953 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3954 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3955 return nullptr;
3956 RD = Base;
3957 }
3958 // Finally cast to the class containing the member.
3959 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3960 MemPtr.getContainingRecord()))
3961 return nullptr;
3962 }
3963
3964 // Add the member. Note that we cannot build bound member functions here.
3965 if (IncludeMember) {
3966 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3967 if (!HandleLValueMember(Info, RHS, LV, FD))
3968 return nullptr;
3969 } else if (const IndirectFieldDecl *IFD =
3970 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3971 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3972 return nullptr;
3973 } else {
3974 llvm_unreachable("can't construct reference to bound member function");
3975 }
3976 }
3977
3978 return MemPtr.getDecl();
3979}
3980
3981static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3982 const BinaryOperator *BO,
3983 LValue &LV,
3984 bool IncludeMember = true) {
3985 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3986
3987 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3988 if (Info.noteFailure()) {
3989 MemberPtr MemPtr;
3990 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3991 }
3992 return nullptr;
3993 }
3994
3995 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3996 BO->getRHS(), IncludeMember);
3997}
3998
3999/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4000/// the provided lvalue, which currently refers to the base object.
4001static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4002 LValue &Result) {
4003 SubobjectDesignator &D = Result.Designator;
4004 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4005 return false;
4006
4007 QualType TargetQT = E->getType();
4008 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4009 TargetQT = PT->getPointeeType();
4010
4011 // Check this cast lands within the final derived-to-base subobject path.
4012 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4013 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4014 << D.MostDerivedType << TargetQT;
4015 return false;
4016 }
4017
4018 // Check the type of the final cast. We don't need to check the path,
4019 // since a cast can only be formed if the path is unique.
4020 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4021 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4022 const CXXRecordDecl *FinalType;
4023 if (NewEntriesSize == D.MostDerivedPathLength)
4024 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4025 else
4026 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4027 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4028 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4029 << D.MostDerivedType << TargetQT;
4030 return false;
4031 }
4032
4033 // Truncate the lvalue to the appropriate derived class.
4034 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4035}
4036
4037namespace {
4038enum EvalStmtResult {
4039 /// Evaluation failed.
4040 ESR_Failed,
4041 /// Hit a 'return' statement.
4042 ESR_Returned,
4043 /// Evaluation succeeded.
4044 ESR_Succeeded,
4045 /// Hit a 'continue' statement.
4046 ESR_Continue,
4047 /// Hit a 'break' statement.
4048 ESR_Break,
4049 /// Still scanning for 'case' or 'default' statement.
4050 ESR_CaseNotFound
4051};
4052}
4053
4054static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4055 // We don't need to evaluate the initializer for a static local.
4056 if (!VD->hasLocalStorage())
4057 return true;
4058
4059 LValue Result;
4060 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
4061
4062 const Expr *InitE = VD->getInit();
4063 if (!InitE) {
4064 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
4065 << false << VD->getType();
4066 Val = APValue();
4067 return false;
4068 }
4069
4070 if (InitE->isValueDependent())
4071 return false;
4072
4073 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4074 // Wipe out any partially-computed value, to allow tracking that this
4075 // evaluation failed.
4076 Val = APValue();
4077 return false;
4078 }
4079
4080 return true;
4081}
4082
4083static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4084 bool OK = true;
4085
4086 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4087 OK &= EvaluateVarDecl(Info, VD);
4088
4089 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4090 for (auto *BD : DD->bindings())
4091 if (auto *VD = BD->getHoldingVar())
4092 OK &= EvaluateDecl(Info, VD);
4093
4094 return OK;
4095}
4096
4097
4098/// Evaluate a condition (either a variable declaration or an expression).
4099static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4100 const Expr *Cond, bool &Result) {
4101 FullExpressionRAII Scope(Info);
4102 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4103 return false;
4104 return EvaluateAsBooleanCondition(Cond, Result, Info);
4105}
4106
4107namespace {
4108/// A location where the result (returned value) of evaluating a
4109/// statement should be stored.
4110struct StmtResult {
4111 /// The APValue that should be filled in with the returned value.
4112 APValue &Value;
4113 /// The location containing the result, if any (used to support RVO).
4114 const LValue *Slot;
4115};
4116
4117struct TempVersionRAII {
4118 CallStackFrame &Frame;
4119
4120 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4121 Frame.pushTempVersion();
4122 }
4123
4124 ~TempVersionRAII() {
4125 Frame.popTempVersion();
4126 }
4127};
4128
4129}
4130
4131static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4132 const Stmt *S,
4133 const SwitchCase *SC = nullptr);
4134
4135/// Evaluate the body of a loop, and translate the result as appropriate.
4136static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4137 const Stmt *Body,
4138 const SwitchCase *Case = nullptr) {
4139 BlockScopeRAII Scope(Info);
4140 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
4141 case ESR_Break:
4142 return ESR_Succeeded;
4143 case ESR_Succeeded:
4144 case ESR_Continue:
4145 return ESR_Continue;
4146 case ESR_Failed:
4147 case ESR_Returned:
4148 case ESR_CaseNotFound:
4149 return ESR;
4150 }
4151 llvm_unreachable("Invalid EvalStmtResult!");
4152}
4153
4154/// Evaluate a switch statement.
4155static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4156 const SwitchStmt *SS) {
4157 BlockScopeRAII Scope(Info);
4158
4159 // Evaluate the switch condition.
4160 APSInt Value;
4161 {
4162 FullExpressionRAII Scope(Info);
4163 if (const Stmt *Init = SS->getInit()) {
4164 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4165 if (ESR != ESR_Succeeded)
4166 return ESR;
4167 }
4168 if (SS->getConditionVariable() &&
4169 !EvaluateDecl(Info, SS->getConditionVariable()))
4170 return ESR_Failed;
4171 if (!EvaluateInteger(SS->getCond(), Value, Info))
4172 return ESR_Failed;
4173 }
4174
4175 // Find the switch case corresponding to the value of the condition.
4176 // FIXME: Cache this lookup.
4177 const SwitchCase *Found = nullptr;
4178 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4179 SC = SC->getNextSwitchCase()) {
4180 if (isa<DefaultStmt>(SC)) {
4181 Found = SC;
4182 continue;
4183 }
4184
4185 const CaseStmt *CS = cast<CaseStmt>(SC);
4186 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4187 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4188 : LHS;
4189 if (LHS <= Value && Value <= RHS) {
4190 Found = SC;
4191 break;
4192 }
4193 }
4194
4195 if (!Found)
4196 return ESR_Succeeded;
4197
4198 // Search the switch body for the switch case and evaluate it from there.
4199 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4200 case ESR_Break:
4201 return ESR_Succeeded;
4202 case ESR_Succeeded:
4203 case ESR_Continue:
4204 case ESR_Failed:
4205 case ESR_Returned:
4206 return ESR;
4207 case ESR_CaseNotFound:
4208 // This can only happen if the switch case is nested within a statement
4209 // expression. We have no intention of supporting that.
4210 Info.FFDiag(Found->getBeginLoc(),
4211 diag::note_constexpr_stmt_expr_unsupported);
4212 return ESR_Failed;
4213 }
4214 llvm_unreachable("Invalid EvalStmtResult!");
4215}
4216
4217// Evaluate a statement.
4218static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4219 const Stmt *S, const SwitchCase *Case) {
4220 if (!Info.nextStep(S))
4221 return ESR_Failed;
4222
4223 // If we're hunting down a 'case' or 'default' label, recurse through
4224 // substatements until we hit the label.
4225 if (Case) {
4226 // FIXME: We don't start the lifetime of objects whose initialization we
4227 // jump over. However, such objects must be of class type with a trivial
4228 // default constructor that initialize all subobjects, so must be empty,
4229 // so this almost never matters.
4230 switch (S->getStmtClass()) {
4231 case Stmt::CompoundStmtClass:
4232 // FIXME: Precompute which substatement of a compound statement we
4233 // would jump to, and go straight there rather than performing a
4234 // linear scan each time.
4235 case Stmt::LabelStmtClass:
4236 case Stmt::AttributedStmtClass:
4237 case Stmt::DoStmtClass:
4238 break;
4239
4240 case Stmt::CaseStmtClass:
4241 case Stmt::DefaultStmtClass:
4242 if (Case == S)
4243 Case = nullptr;
4244 break;
4245
4246 case Stmt::IfStmtClass: {
4247 // FIXME: Precompute which side of an 'if' we would jump to, and go
4248 // straight there rather than scanning both sides.
4249 const IfStmt *IS = cast<IfStmt>(S);
4250
4251 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4252 // preceded by our switch label.
4253 BlockScopeRAII Scope(Info);
4254
4255 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4256 if (ESR != ESR_CaseNotFound || !IS->getElse())
4257 return ESR;
4258 return EvaluateStmt(Result, Info, IS->getElse(), Case);
4259 }
4260
4261 case Stmt::WhileStmtClass: {
4262 EvalStmtResult ESR =
4263 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4264 if (ESR != ESR_Continue)
4265 return ESR;
4266 break;
4267 }
4268
4269 case Stmt::ForStmtClass: {
4270 const ForStmt *FS = cast<ForStmt>(S);
4271 EvalStmtResult ESR =
4272 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4273 if (ESR != ESR_Continue)
4274 return ESR;
4275 if (FS->getInc()) {
4276 FullExpressionRAII IncScope(Info);
4277 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4278 return ESR_Failed;
4279 }
4280 break;
4281 }
4282
4283 case Stmt::DeclStmtClass:
4284 // FIXME: If the variable has initialization that can't be jumped over,
4285 // bail out of any immediately-surrounding compound-statement too.
4286 default:
4287 return ESR_CaseNotFound;
4288 }
4289 }
4290
4291 switch (S->getStmtClass()) {
4292 default:
4293 if (const Expr *E = dyn_cast<Expr>(S)) {
4294 // Don't bother evaluating beyond an expression-statement which couldn't
4295 // be evaluated.
4296 FullExpressionRAII Scope(Info);
4297 if (!EvaluateIgnoredValue(Info, E))
4298 return ESR_Failed;
4299 return ESR_Succeeded;
4300 }
4301
4302 Info.FFDiag(S->getBeginLoc());
4303 return ESR_Failed;
4304
4305 case Stmt::NullStmtClass:
4306 return ESR_Succeeded;
4307
4308 case Stmt::DeclStmtClass: {
4309 const DeclStmt *DS = cast<DeclStmt>(S);
4310 for (const auto *DclIt : DS->decls()) {
4311 // Each declaration initialization is its own full-expression.
4312 // FIXME: This isn't quite right; if we're performing aggregate
4313 // initialization, each braced subexpression is its own full-expression.
4314 FullExpressionRAII Scope(Info);
4315 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
4316 return ESR_Failed;
4317 }
4318 return ESR_Succeeded;
4319 }
4320
4321 case Stmt::ReturnStmtClass: {
4322 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4323 FullExpressionRAII Scope(Info);
4324 if (RetExpr &&
4325 !(Result.Slot
4326 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4327 : Evaluate(Result.Value, Info, RetExpr)))
4328 return ESR_Failed;
4329 return ESR_Returned;
4330 }
4331
4332 case Stmt::CompoundStmtClass: {
4333 BlockScopeRAII Scope(Info);
4334
4335 const CompoundStmt *CS = cast<CompoundStmt>(S);
4336 for (const auto *BI : CS->body()) {
4337 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4338 if (ESR == ESR_Succeeded)
4339 Case = nullptr;
4340 else if (ESR != ESR_CaseNotFound)
4341 return ESR;
4342 }
4343 return Case ? ESR_CaseNotFound : ESR_Succeeded;
4344 }
4345
4346 case Stmt::IfStmtClass: {
4347 const IfStmt *IS = cast<IfStmt>(S);
4348
4349 // Evaluate the condition, as either a var decl or as an expression.
4350 BlockScopeRAII Scope(Info);
4351 if (const Stmt *Init = IS->getInit()) {
4352 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4353 if (ESR != ESR_Succeeded)
4354 return ESR;
4355 }
4356 bool Cond;
4357 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4358 return ESR_Failed;
4359
4360 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4361 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4362 if (ESR != ESR_Succeeded)
4363 return ESR;
4364 }
4365 return ESR_Succeeded;
4366 }
4367
4368 case Stmt::WhileStmtClass: {
4369 const WhileStmt *WS = cast<WhileStmt>(S);
4370 while (true) {
4371 BlockScopeRAII Scope(Info);
4372 bool Continue;
4373 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4374 Continue))
4375 return ESR_Failed;
4376 if (!Continue)
4377 break;
4378
4379 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4380 if (ESR != ESR_Continue)
4381 return ESR;
4382 }
4383 return ESR_Succeeded;
4384 }
4385
4386 case Stmt::DoStmtClass: {
4387 const DoStmt *DS = cast<DoStmt>(S);
4388 bool Continue;
4389 do {
4390 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4391 if (ESR != ESR_Continue)
4392 return ESR;
4393 Case = nullptr;
4394
4395 FullExpressionRAII CondScope(Info);
4396 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4397 return ESR_Failed;
4398 } while (Continue);
4399 return ESR_Succeeded;
4400 }
4401
4402 case Stmt::ForStmtClass: {
4403 const ForStmt *FS = cast<ForStmt>(S);
4404 BlockScopeRAII Scope(Info);
4405 if (FS->getInit()) {
4406 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4407 if (ESR != ESR_Succeeded)
4408 return ESR;
4409 }
4410 while (true) {
4411 BlockScopeRAII Scope(Info);
4412 bool Continue = true;
4413 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4414 FS->getCond(), Continue))
4415 return ESR_Failed;
4416 if (!Continue)
4417 break;
4418
4419 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4420 if (ESR != ESR_Continue)
4421 return ESR;
4422
4423 if (FS->getInc()) {
4424 FullExpressionRAII IncScope(Info);
4425 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4426 return ESR_Failed;
4427 }
4428 }
4429 return ESR_Succeeded;
4430 }
4431
4432 case Stmt::CXXForRangeStmtClass: {
4433 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4434 BlockScopeRAII Scope(Info);
4435
4436 // Evaluate the init-statement if present.
4437 if (FS->getInit()) {
4438 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4439 if (ESR != ESR_Succeeded)
4440 return ESR;
4441 }
4442
4443 // Initialize the __range variable.
4444 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4445 if (ESR != ESR_Succeeded)
4446 return ESR;
4447
4448 // Create the __begin and __end iterators.
4449 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4450 if (ESR != ESR_Succeeded)
4451 return ESR;
4452 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4453 if (ESR != ESR_Succeeded)
4454 return ESR;
4455
4456 while (true) {
4457 // Condition: __begin != __end.
4458 {
4459 bool Continue = true;
4460 FullExpressionRAII CondExpr(Info);
4461 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4462 return ESR_Failed;
4463 if (!Continue)
4464 break;
4465 }
4466
4467 // User's variable declaration, initialized by *__begin.
4468 BlockScopeRAII InnerScope(Info);
4469 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4470 if (ESR != ESR_Succeeded)
4471 return ESR;
4472
4473 // Loop body.
4474 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4475 if (ESR != ESR_Continue)
4476 return ESR;
4477
4478 // Increment: ++__begin
4479 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4480 return ESR_Failed;
4481 }
4482
4483 return ESR_Succeeded;
4484 }
4485
4486 case Stmt::SwitchStmtClass:
4487 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4488
4489 case Stmt::ContinueStmtClass:
4490 return ESR_Continue;
4491
4492 case Stmt::BreakStmtClass:
4493 return ESR_Break;
4494
4495 case Stmt::LabelStmtClass:
4496 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4497
4498 case Stmt::AttributedStmtClass:
4499 // As a general principle, C++11 attributes can be ignored without
4500 // any semantic impact.
4501 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4502 Case);
4503
4504 case Stmt::CaseStmtClass:
4505 case Stmt::DefaultStmtClass:
4506 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4507 case Stmt::CXXTryStmtClass:
4508 // Evaluate try blocks by evaluating all sub statements.
4509 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
4510 }
4511}
4512
4513/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4514/// default constructor. If so, we'll fold it whether or not it's marked as
4515/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4516/// so we need special handling.
4517static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4518 const CXXConstructorDecl *CD,
4519 bool IsValueInitialization) {
4520 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4521 return false;
4522
4523 // Value-initialization does not call a trivial default constructor, so such a
4524 // call is a core constant expression whether or not the constructor is
4525 // constexpr.
4526 if (!CD->isConstexpr() && !IsValueInitialization) {
4527 if (Info.getLangOpts().CPlusPlus11) {
4528 // FIXME: If DiagDecl is an implicitly-declared special member function,
4529 // we should be much more explicit about why it's not constexpr.
4530 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4531 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4532 Info.Note(CD->getLocation(), diag::note_declared_at);
4533 } else {
4534 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4535 }
4536 }
4537 return true;
4538}
4539
4540/// CheckConstexprFunction - Check that a function can be called in a constant
4541/// expression.
4542static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4543 const FunctionDecl *Declaration,
4544 const FunctionDecl *Definition,
4545 const Stmt *Body) {
4546 // Potential constant expressions can contain calls to declared, but not yet
4547 // defined, constexpr functions.
4548 if (Info.checkingPotentialConstantExpression() && !Definition &&
4549 Declaration->isConstexpr())
4550 return false;
4551
4552 // Bail out if the function declaration itself is invalid. We will
4553 // have produced a relevant diagnostic while parsing it, so just
4554 // note the problematic sub-expression.
4555 if (Declaration->isInvalidDecl()) {
4556 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4557 return false;
4558 }
4559
4560 // DR1872: An instantiated virtual constexpr function can't be called in a
4561 // constant expression (prior to C++20). We can still constant-fold such a
4562 // call.
4563 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4564 cast<CXXMethodDecl>(Declaration)->isVirtual())
4565 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4566
4567 if (Definition && Definition->isInvalidDecl()) {
4568 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4569 return false;
4570 }
4571
4572 // Can we evaluate this function call?
4573 if (Definition && Definition->isConstexpr() && Body)
4574 return true;
4575
4576 if (Info.getLangOpts().CPlusPlus11) {
4577 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4578
4579 // If this function is not constexpr because it is an inherited
4580 // non-constexpr constructor, diagnose that directly.
4581 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4582 if (CD && CD->isInheritingConstructor()) {
4583 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4584 if (!Inherited->isConstexpr())
4585 DiagDecl = CD = Inherited;
4586 }
4587
4588 // FIXME: If DiagDecl is an implicitly-declared special member function
4589 // or an inheriting constructor, we should be much more explicit about why
4590 // it's not constexpr.
4591 if (CD && CD->isInheritingConstructor())
4592 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4593 << CD->getInheritedConstructor().getConstructor()->getParent();
4594 else
4595 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4596 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4597 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4598 } else {
4599 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4600 }
4601 return false;
4602}
4603
4604namespace {
4605struct CheckDynamicTypeHandler {
4606 AccessKinds AccessKind;
4607 typedef bool result_type;
4608 bool failed() { return false; }
4609 bool found(APValue &Subobj, QualType SubobjType) { return true; }
4610 bool found(APSInt &Value, QualType SubobjType) { return true; }
4611 bool found(APFloat &Value, QualType SubobjType) { return true; }
4612};
4613} // end anonymous namespace
4614
4615/// Check that we can access the notional vptr of an object / determine its
4616/// dynamic type.
4617static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4618 AccessKinds AK, bool Polymorphic) {
4619 if (This.Designator.Invalid)
4620 return false;
4621
4622 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
4623
4624 if (!Obj)
4625 return false;
4626
4627 if (!Obj.Value) {
4628 // The object is not usable in constant expressions, so we can't inspect
4629 // its value to see if it's in-lifetime or what the active union members
4630 // are. We can still check for a one-past-the-end lvalue.
4631 if (This.Designator.isOnePastTheEnd() ||
4632 This.Designator.isMostDerivedAnUnsizedArray()) {
4633 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4634 ? diag::note_constexpr_access_past_end
4635 : diag::note_constexpr_access_unsized_array)
4636 << AK;
4637 return false;
4638 } else if (Polymorphic) {
4639 // Conservatively refuse to perform a polymorphic operation if we would
4640 // not be able to read a notional 'vptr' value.
4641 APValue Val;
4642 This.moveInto(Val);
4643 QualType StarThisType =
4644 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
4645 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4646 << AK << Val.getAsString(Info.Ctx, StarThisType);
4647 return false;
4648 }
4649 return true;
4650 }
4651
4652 CheckDynamicTypeHandler Handler{AK};
4653 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4654}
4655
4656/// Check that the pointee of the 'this' pointer in a member function call is
4657/// either within its lifetime or in its period of construction or destruction.
4658static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
4659 const LValue &This) {
4660 return checkDynamicType(Info, E, This, AK_MemberCall, false);
4661}
4662
4663struct DynamicType {
4664 /// The dynamic class type of the object.
4665 const CXXRecordDecl *Type;
4666 /// The corresponding path length in the lvalue.
4667 unsigned PathLength;
4668};
4669
4670static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
4671 unsigned PathLength) {
4672 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
4673 Designator.Entries.size() && "invalid path length");
4674 return (PathLength == Designator.MostDerivedPathLength)
4675 ? Designator.MostDerivedType->getAsCXXRecordDecl()
4676 : getAsBaseClass(Designator.Entries[PathLength - 1]);
4677}
4678
4679/// Determine the dynamic type of an object.
4680static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
4681 LValue &This, AccessKinds AK) {
4682 // If we don't have an lvalue denoting an object of class type, there is no
4683 // meaningful dynamic type. (We consider objects of non-class type to have no
4684 // dynamic type.)
4685 if (!checkDynamicType(Info, E, This, AK, true))
4686 return None;
4687
4688 // Refuse to compute a dynamic type in the presence of virtual bases. This
4689 // shouldn't happen other than in constant-folding situations, since literal
4690 // types can't have virtual bases.
4691 //
4692 // Note that consumers of DynamicType assume that the type has no virtual
4693 // bases, and will need modifications if this restriction is relaxed.
4694 const CXXRecordDecl *Class =
4695 This.Designator.MostDerivedType->getAsCXXRecordDecl();
4696 if (!Class || Class->getNumVBases()) {
4697 Info.FFDiag(E);
4698 return None;
4699 }
4700
4701 // FIXME: For very deep class hierarchies, it might be beneficial to use a
4702 // binary search here instead. But the overwhelmingly common case is that
4703 // we're not in the middle of a constructor, so it probably doesn't matter
4704 // in practice.
4705 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
4706 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
4707 PathLength <= Path.size(); ++PathLength) {
4708 switch (Info.isEvaluatingConstructor(This.getLValueBase(),
4709 Path.slice(0, PathLength))) {
4710 case ConstructionPhase::Bases:
4711 // We're constructing a base class. This is not the dynamic type.
4712 break;
4713
4714 case ConstructionPhase::None:
4715 case ConstructionPhase::AfterBases:
4716 // We've finished constructing the base classes, so this is the dynamic
4717 // type.
4718 return DynamicType{getBaseClassType(This.Designator, PathLength),
4719 PathLength};
4720 }
4721 }
4722
4723 // CWG issue 1517: we're constructing a base class of the object described by
4724 // 'This', so that object has not yet begun its period of construction and
4725 // any polymorphic operation on it results in undefined behavior.
4726 Info.FFDiag(E);
4727 return None;
4728}
4729
4730/// Perform virtual dispatch.
4731static const CXXMethodDecl *HandleVirtualDispatch(
4732 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
4733 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
4734 Optional<DynamicType> DynType =
4735 ComputeDynamicType(Info, E, This, AK_MemberCall);
4736 if (!DynType)
4737 return nullptr;
4738
4739 // Find the final overrider. It must be declared in one of the classes on the
4740 // path from the dynamic type to the static type.
4741 // FIXME: If we ever allow literal types to have virtual base classes, that
4742 // won't be true.
4743 const CXXMethodDecl *Callee = Found;
4744 unsigned PathLength = DynType->PathLength;
4745 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
4746 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
4747 const CXXMethodDecl *Overrider =
4748 Found->getCorrespondingMethodDeclaredInClass(Class, false);
4749 if (Overrider) {
4750 Callee = Overrider;
4751 break;
4752 }
4753 }
4754
4755 // C++2a [class.abstract]p6:
4756 // the effect of making a virtual call to a pure virtual function [...] is
4757 // undefined
4758 if (Callee->isPure()) {
4759 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
4760 Info.Note(Callee->getLocation(), diag::note_declared_at);
4761 return nullptr;
4762 }
4763
4764 // If necessary, walk the rest of the path to determine the sequence of
4765 // covariant adjustment steps to apply.
4766 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
4767 Found->getReturnType())) {
4768 CovariantAdjustmentPath.push_back(Callee->getReturnType());
4769 for (unsigned CovariantPathLength = PathLength + 1;
4770 CovariantPathLength != This.Designator.Entries.size();
4771 ++CovariantPathLength) {
4772 const CXXRecordDecl *NextClass =
4773 getBaseClassType(This.Designator, CovariantPathLength);
4774 const CXXMethodDecl *Next =
4775 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
4776 if (Next && !Info.Ctx.hasSameUnqualifiedType(
4777 Next->getReturnType(), CovariantAdjustmentPath.back()))
4778 CovariantAdjustmentPath.push_back(Next->getReturnType());
4779 }
4780 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
4781 CovariantAdjustmentPath.back()))
4782 CovariantAdjustmentPath.push_back(Found->getReturnType());
4783 }
4784
4785 // Perform 'this' adjustment.
4786 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
4787 return nullptr;
4788
4789 return Callee;
4790}
4791
4792/// Perform the adjustment from a value returned by a virtual function to
4793/// a value of the statically expected type, which may be a pointer or
4794/// reference to a base class of the returned type.
4795static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
4796 APValue &Result,
4797 ArrayRef<QualType> Path) {
4798 assert(Result.isLValue() &&
4799 "unexpected kind of APValue for covariant return");
4800 if (Result.isNullPointer())
4801 return true;
4802
4803 LValue LVal;
4804 LVal.setFrom(Info.Ctx, Result);
4805
4806 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
4807 for (unsigned I = 1; I != Path.size(); ++I) {
4808 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
4809 assert(OldClass && NewClass && "unexpected kind of covariant return");
4810 if (OldClass != NewClass &&
4811 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
4812 return false;
4813 OldClass = NewClass;
4814 }
4815
4816 LVal.moveInto(Result);
4817 return true;
4818}
4819
4820/// Determine whether \p Base, which is known to be a direct base class of
4821/// \p Derived, is a public base class.
4822static bool isBaseClassPublic(const CXXRecordDecl *Derived,
4823 const CXXRecordDecl *Base) {
4824 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
4825 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
4826 if (BaseClass && declaresSameEntity(BaseClass, Base))
4827 return BaseSpec.getAccessSpecifier() == AS_public;
4828 }
4829 llvm_unreachable("Base is not a direct base of Derived");
4830}
4831
4832/// Apply the given dynamic cast operation on the provided lvalue.
4833///
4834/// This implements the hard case of dynamic_cast, requiring a "runtime check"
4835/// to find a suitable target subobject.
4836static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
4837 LValue &Ptr) {
4838 // We can't do anything with a non-symbolic pointer value.
4839 SubobjectDesignator &D = Ptr.Designator;
4840 if (D.Invalid)
4841 return false;
4842
4843 // C++ [expr.dynamic.cast]p6:
4844 // If v is a null pointer value, the result is a null pointer value.
4845 if (Ptr.isNullPointer() && !E->isGLValue())
4846 return true;
4847
4848 // For all the other cases, we need the pointer to point to an object within
4849 // its lifetime / period of construction / destruction, and we need to know
4850 // its dynamic type.
4851 Optional<DynamicType> DynType =
4852 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
4853 if (!DynType)
4854 return false;
4855
4856 // C++ [expr.dynamic.cast]p7:
4857 // If T is "pointer to cv void", then the result is a pointer to the most
4858 // derived object
4859 if (E->getType()->isVoidPointerType())
4860 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
4861
4862 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
4863 assert(C && "dynamic_cast target is not void pointer nor class");
4864 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
4865
4866 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
4867 // C++ [expr.dynamic.cast]p9:
4868 if (!E->isGLValue()) {
4869 // The value of a failed cast to pointer type is the null pointer value
4870 // of the required result type.
4871 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
4872 Ptr.setNull(E->getType(), TargetVal);
4873 return true;
4874 }
4875
4876 // A failed cast to reference type throws [...] std::bad_cast.
4877 unsigned DiagKind;
4878 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
4879 DynType->Type->isDerivedFrom(C)))
4880 DiagKind = 0;
4881 else if (!Paths || Paths->begin() == Paths->end())
4882 DiagKind = 1;
4883 else if (Paths->isAmbiguous(CQT))
4884 DiagKind = 2;
4885 else {
4886 assert(Paths->front().Access != AS_public && "why did the cast fail?");
4887 DiagKind = 3;
4888 }
4889 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
4890 << DiagKind << Ptr.Designator.getType(Info.Ctx)
4891 << Info.Ctx.getRecordType(DynType->Type)
4892 << E->getType().getUnqualifiedType();
4893 return false;
4894 };
4895
4896 // Runtime check, phase 1:
4897 // Walk from the base subobject towards the derived object looking for the
4898 // target type.
4899 for (int PathLength = Ptr.Designator.Entries.size();
4900 PathLength >= (int)DynType->PathLength; --PathLength) {
4901 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
4902 if (declaresSameEntity(Class, C))
4903 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
4904 // We can only walk across public inheritance edges.
4905 if (PathLength > (int)DynType->PathLength &&
4906 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
4907 Class))
4908 return RuntimeCheckFailed(nullptr);
4909 }
4910
4911 // Runtime check, phase 2:
4912 // Search the dynamic type for an unambiguous public base of type C.
4913 CXXBasePaths Paths(/*FindAmbiguities=*/true,
4914 /*RecordPaths=*/true, /*DetectVirtual=*/false);
4915 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
4916 Paths.front().Access == AS_public) {
4917 // Downcast to the dynamic type...
4918 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
4919 return false;
4920 // ... then upcast to the chosen base class subobject.
4921 for (CXXBasePathElement &Elem : Paths.front())
4922 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
4923 return false;
4924 return true;
4925 }
4926
4927 // Otherwise, the runtime check fails.
4928 return RuntimeCheckFailed(&Paths);
4929}
4930
4931namespace {
4932struct StartLifetimeOfUnionMemberHandler {
4933 const FieldDecl *Field;
4934
4935 static const AccessKinds AccessKind = AK_Assign;
4936
4937 APValue getDefaultInitValue(QualType SubobjType) {
4938 if (auto *RD = SubobjType->getAsCXXRecordDecl()) {
4939 if (RD->isUnion())
4940 return APValue((const FieldDecl*)nullptr);
4941
4942 APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4943 std::distance(RD->field_begin(), RD->field_end()));
4944
4945 unsigned Index = 0;
4946 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4947 End = RD->bases_end(); I != End; ++I, ++Index)
4948 Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4949
4950 for (const auto *I : RD->fields()) {
4951 if (I->isUnnamedBitfield())
4952 continue;
4953 Struct.getStructField(I->getFieldIndex()) =
4954 getDefaultInitValue(I->getType());
4955 }
4956 return Struct;
4957 }
4958
4959 if (auto *AT = dyn_cast_or_null<ConstantArrayType>(
4960 SubobjType->getAsArrayTypeUnsafe())) {
4961 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4962 if (Array.hasArrayFiller())
4963 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4964 return Array;
4965 }
4966
4967 return APValue::IndeterminateValue();
4968 }
4969
4970 typedef bool result_type;
4971 bool failed() { return false; }
4972 bool found(APValue &Subobj, QualType SubobjType) {
4973 // We are supposed to perform no initialization but begin the lifetime of
4974 // the object. We interpret that as meaning to do what default
4975 // initialization of the object would do if all constructors involved were
4976 // trivial:
4977 // * All base, non-variant member, and array element subobjects' lifetimes
4978 // begin
4979 // * No variant members' lifetimes begin
4980 // * All scalar subobjects whose lifetimes begin have indeterminate values
4981 assert(SubobjType->isUnionType());
4982 if (!declaresSameEntity(Subobj.getUnionField(), Field))
4983 Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
4984 return true;
4985 }
4986 bool found(APSInt &Value, QualType SubobjType) {
4987 llvm_unreachable("wrong value kind for union object");
4988 }
4989 bool found(APFloat &Value, QualType SubobjType) {
4990 llvm_unreachable("wrong value kind for union object");
4991 }
4992};
4993} // end anonymous namespace
4994
4995const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
4996
4997/// Handle a builtin simple-assignment or a call to a trivial assignment
4998/// operator whose left-hand side might involve a union member access. If it
4999/// does, implicitly start the lifetime of any accessed union elements per
5000/// C++20 [class.union]5.
5001static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5002 const LValue &LHS) {
5003 if (LHS.InvalidBase || LHS.Designator.Invalid)
5004 return false;
5005
5006 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5007 // C++ [class.union]p5:
5008 // define the set S(E) of subexpressions of E as follows:
5009 unsigned PathLength = LHS.Designator.Entries.size();
5010 for (const Expr *E = LHSExpr; E != nullptr;) {
5011 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
5012 if (auto *ME = dyn_cast<MemberExpr>(E)) {
5013 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5014 if (!FD)
5015 break;
5016
5017 // ... and also contains A.B if B names a union member
5018 if (FD->getParent()->isUnion())
5019 UnionPathLengths.push_back({PathLength - 1, FD});
5020
5021 E = ME->getBase();
5022 --PathLength;
5023 assert(declaresSameEntity(FD,
5024 LHS.Designator.Entries[PathLength]
5025 .getAsBaseOrMember().getPointer()));
5026
5027 // -- If E is of the form A[B] and is interpreted as a built-in array
5028 // subscripting operator, S(E) is [S(the array operand, if any)].
5029 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5030 // Step over an ArrayToPointerDecay implicit cast.
5031 auto *Base = ASE->getBase()->IgnoreImplicit();
5032 if (!Base->getType()->isArrayType())
5033 break;
5034
5035 E = Base;
5036 --PathLength;
5037
5038 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5039 // Step over a derived-to-base conversion.
5040 E = ICE->getSubExpr();
5041 if (ICE->getCastKind() == CK_NoOp)
5042 continue;
5043 if (ICE->getCastKind() != CK_DerivedToBase &&
5044 ICE->getCastKind() != CK_UncheckedDerivedToBase)
5045 break;
5046 // Walk path backwards as we walk up from the base to the derived class.
5047 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5048 --PathLength;
5049 (void)Elt;
5050 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5051 LHS.Designator.Entries[PathLength]
5052 .getAsBaseOrMember().getPointer()));
5053 }
5054
5055 // -- Otherwise, S(E) is empty.
5056 } else {
5057 break;
5058 }
5059 }
5060
5061 // Common case: no unions' lifetimes are started.
5062 if (UnionPathLengths.empty())
5063 return true;
5064
5065 // if modification of X [would access an inactive union member], an object
5066 // of the type of X is implicitly created
5067 CompleteObject Obj =
5068 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5069 if (!Obj)
5070 return false;
5071 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5072 llvm::reverse(UnionPathLengths)) {
5073 // Form a designator for the union object.
5074 SubobjectDesignator D = LHS.Designator;
5075 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5076
5077 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
5078 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5079 return false;
5080 }
5081
5082 return true;
5083}
5084
5085/// Determine if a class has any fields that might need to be copied by a
5086/// trivial copy or move operation.
5087static bool hasFields(const CXXRecordDecl *RD) {
5088 if (!RD || RD->isEmpty())
5089 return false;
5090 for (auto *FD : RD->fields()) {
5091 if (FD->isUnnamedBitfield())
5092 continue;
5093 return true;
5094 }
5095 for (auto &Base : RD->bases())
5096 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
5097 return true;
5098 return false;
5099}
5100
5101namespace {
5102typedef SmallVector<APValue, 8> ArgVector;
5103}
5104
5105/// EvaluateArgs - Evaluate the arguments to a function call.
5106static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
5107 EvalInfo &Info) {
5108 bool Success = true;
5109 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
5110 I != E; ++I) {
5111 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
5112 // If we're checking for a potential constant expression, evaluate all
5113 // initializers even if some of them fail.
5114 if (!Info.noteFailure())
5115 return false;
5116 Success = false;
5117 }
5118 }
5119 return Success;
5120}
5121
5122/// Evaluate a function call.
5123static bool HandleFunctionCall(SourceLocation CallLoc,
5124 const FunctionDecl *Callee, const LValue *This,
5125 ArrayRef<const Expr*> Args, const Stmt *Body,
5126 EvalInfo &Info, APValue &Result,
5127 const LValue *ResultSlot) {
5128 ArgVector ArgValues(Args.size());
5129 if (!EvaluateArgs(Args, ArgValues, Info))
5130 return false;
5131
5132 if (!Info.CheckCallLimit(CallLoc))
5133 return false;
5134
5135 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5136
5137 // For a trivial copy or move assignment, perform an APValue copy. This is
5138 // essential for unions, where the operations performed by the assignment
5139 // operator cannot be represented as statements.
5140 //
5141 // Skip this for non-union classes with no fields; in that case, the defaulted
5142 // copy/move does not actually read the object.
5143 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
5144 if (MD && MD->isDefaulted() &&
5145 (MD->getParent()->isUnion() ||
5146 (MD->isTrivial() && hasFields(MD->getParent())))) {
5147 assert(This &&
5148 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5149 LValue RHS;
5150 RHS.setFrom(Info.Ctx, ArgValues[0]);
5151 APValue RHSValue;
5152 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
5153 RHS, RHSValue))
5154 return false;
5155 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5156 !HandleUnionActiveMemberChange(Info, Args[0], *This))
5157 return false;
5158 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5159 RHSValue))
5160 return false;
5161 This->moveInto(Result);
5162 return true;
5163 } else if (MD && isLambdaCallOperator(MD)) {
5164 // We're in a lambda; determine the lambda capture field maps unless we're
5165 // just constexpr checking a lambda's call operator. constexpr checking is
5166 // done before the captures have been added to the closure object (unless
5167 // we're inferring constexpr-ness), so we don't have access to them in this
5168 // case. But since we don't need the captures to constexpr check, we can
5169 // just ignore them.
5170 if (!Info.checkingPotentialConstantExpression())
5171 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5172 Frame.LambdaThisCaptureField);
5173 }
5174
5175 StmtResult Ret = {Result, ResultSlot};
5176 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5177 if (ESR == ESR_Succeeded) {
5178 if (Callee->getReturnType()->isVoidType())
5179 return true;
5180 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5181 }
5182 return ESR == ESR_Returned;
5183}
5184
5185/// Evaluate a constructor call.
5186static bool HandleConstructorCall(const Expr *E, const LValue &This,
5187 APValue *ArgValues,
5188 const CXXConstructorDecl *Definition,
5189 EvalInfo &Info, APValue &Result) {
5190 SourceLocation CallLoc = E->getExprLoc();
5191 if (!Info.CheckCallLimit(CallLoc))
5192 return false;
5193
5194 const CXXRecordDecl *RD = Definition->getParent();
5195 if (RD->getNumVBases()) {
5196 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5197 return false;
5198 }
5199
5200 EvalInfo::EvaluatingConstructorRAII EvalObj(
5201 Info,
5202 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5203 RD->getNumBases());
5204 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5205
5206 // FIXME: Creating an APValue just to hold a nonexistent return value is
5207 // wasteful.
5208 APValue RetVal;
5209 StmtResult Ret = {RetVal, nullptr};
5210
5211 // If it's a delegating constructor, delegate.
5212 if (Definition->isDelegatingConstructor()) {
5213 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5214 {
5215 FullExpressionRAII InitScope(Info);
5216 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
5217 return false;
5218 }
5219 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5220 }
5221
5222 // For a trivial copy or move constructor, perform an APValue copy. This is
5223 // essential for unions (or classes with anonymous union members), where the
5224 // operations performed by the constructor cannot be represented by
5225 // ctor-initializers.
5226 //
5227 // Skip this for empty non-union classes; we should not perform an
5228 // lvalue-to-rvalue conversion on them because their copy constructor does not
5229 // actually read them.
5230 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5231 (Definition->getParent()->isUnion() ||
5232 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
5233 LValue RHS;
5234 RHS.setFrom(Info.Ctx, ArgValues[0]);
5235 return handleLValueToRValueConversion(
5236 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5237 RHS, Result);
5238 }
5239
5240 // Reserve space for the struct members.
5241 if (!RD->isUnion() && !Result.hasValue())
5242 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5243 std::distance(RD->field_begin(), RD->field_end()));
5244
5245 if (RD->isInvalidDecl()) return false;
5246 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5247
5248 // A scope for temporaries lifetime-extended by reference members.
5249 BlockScopeRAII LifetimeExtendedScope(Info);
5250
5251 bool Success = true;
5252 unsigned BasesSeen = 0;
5253#ifndef NDEBUG
5254 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5255#endif
5256 for (const auto *I : Definition->inits()) {
5257 LValue Subobject = This;
5258 LValue SubobjectParent = This;
5259 APValue *Value = &Result;
5260
5261 // Determine the subobject to initialize.
5262 FieldDecl *FD = nullptr;
5263 if (I->isBaseInitializer()) {
5264 QualType BaseType(I->getBaseClass(), 0);
5265#ifndef NDEBUG
5266 // Non-virtual base classes are initialized in the order in the class
5267 // definition. We have already checked for virtual base classes.
5268 assert(!BaseIt->isVirtual() && "virtual base for literal type");
5269 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5270 "base class initializers not in expected order");
5271 ++BaseIt;
5272#endif
5273 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
5274 BaseType->getAsCXXRecordDecl(), &Layout))
5275 return false;
5276 Value = &Result.getStructBase(BasesSeen++);
5277 } else if ((FD = I->getMember())) {
5278 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
5279 return false;
5280 if (RD->isUnion()) {
5281 Result = APValue(FD);
5282 Value = &Result.getUnionValue();
5283 } else {
5284 Value = &Result.getStructField(FD->getFieldIndex());
5285 }
5286 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
5287 // Walk the indirect field decl's chain to find the object to initialize,
5288 // and make sure we've initialized every step along it.
5289 auto IndirectFieldChain = IFD->chain();
5290 for (auto *C : IndirectFieldChain) {
5291 FD = cast<FieldDecl>(C);
5292 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5293 // Switch the union field if it differs. This happens if we had
5294 // preceding zero-initialization, and we're now initializing a union
5295 // subobject other than the first.
5296 // FIXME: In this case, the values of the other subobjects are
5297 // specified, since zero-initialization sets all padding bits to zero.
5298 if (!Value->hasValue() ||
5299 (Value->isUnion() && Value->getUnionField() != FD)) {
5300 if (CD->isUnion())
5301 *Value = APValue(FD);
5302 else
5303 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
5304 std::distance(CD->field_begin(), CD->field_end()));
5305 }
5306 // Store Subobject as its parent before updating it for the last element
5307 // in the chain.
5308 if (C == IndirectFieldChain.back())
5309 SubobjectParent = Subobject;
5310 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
5311 return false;
5312 if (CD->isUnion())
5313 Value = &Value->getUnionValue();
5314 else
5315 Value = &Value->getStructField(FD->getFieldIndex());
5316 }
5317 } else {
5318 llvm_unreachable("unknown base initializer kind");
5319 }
5320
5321 // Need to override This for implicit field initializers as in this case
5322 // This refers to innermost anonymous struct/union containing initializer,
5323 // not to currently constructed class.
5324 const Expr *Init = I->getInit();
5325 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5326 isa<CXXDefaultInitExpr>(Init));
5327 FullExpressionRAII InitScope(Info);
5328 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5329 (FD && FD->isBitField() &&
5330 !truncateBitfieldValue(Info, Init, *Value, FD))) {
5331 // If we're checking for a potential constant expression, evaluate all
5332 // initializers even if some of them fail.
5333 if (!Info.noteFailure())
5334 return false;
5335 Success = false;
5336 }
5337
5338 // This is the point at which the dynamic type of the object becomes this
5339 // class type.
5340 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5341 EvalObj.finishedConstructingBases();
5342 }
5343
5344 return Success &&
5345 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5346}
5347
5348static bool HandleConstructorCall(const Expr *E, const LValue &This,
5349 ArrayRef<const Expr*> Args,
5350 const CXXConstructorDecl *Definition,
5351 EvalInfo &Info, APValue &Result) {
5352 ArgVector ArgValues(Args.size());
5353 if (!EvaluateArgs(Args, ArgValues, Info))
5354 return false;
5355
5356 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5357 Info, Result);
5358}
5359
5360//===----------------------------------------------------------------------===//
5361// Generic Evaluation
5362//===----------------------------------------------------------------------===//
5363namespace {
5364
5365template <class Derived>
5366class ExprEvaluatorBase
5367 : public ConstStmtVisitor<Derived, bool> {
5368private:
5369 Derived &getDerived() { return static_cast<Derived&>(*this); }
5370 bool DerivedSuccess(const APValue &V, const Expr *E) {
5371 return getDerived().Success(V, E);
5372 }
5373 bool DerivedZeroInitialization(const Expr *E) {
5374 return getDerived().ZeroInitialization(E);
5375 }
5376
5377 // Check whether a conditional operator with a non-constant condition is a
5378 // potential constant expression. If neither arm is a potential constant
5379 // expression, then the conditional operator is not either.
5380 template<typename ConditionalOperator>
5381 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
5382 assert(Info.checkingPotentialConstantExpression());
5383
5384 // Speculatively evaluate both arms.
5385 SmallVector<PartialDiagnosticAt, 8> Diag;
5386 {
5387 SpeculativeEvaluationRAII Speculate(Info, &Diag);
5388 StmtVisitorTy::Visit(E->getFalseExpr());
5389 if (Diag.empty())
5390 return;
5391 }
5392
5393 {
5394 SpeculativeEvaluationRAII Speculate(Info, &Diag);
5395 Diag.clear();
5396 StmtVisitorTy::Visit(E->getTrueExpr());
5397 if (Diag.empty())
5398 return;
5399 }
5400
5401 Error(E, diag::note_constexpr_conditional_never_const);
5402 }
5403
5404
5405 template<typename ConditionalOperator>
5406 bool HandleConditionalOperator(const ConditionalOperator *E) {
5407 bool BoolResult;
5408 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
5409 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
5410 CheckPotentialConstantConditional(E);
5411 return false;
5412 }
5413 if (Info.noteFailure()) {
5414 StmtVisitorTy::Visit(E->getTrueExpr());
5415 StmtVisitorTy::Visit(E->getFalseExpr());
5416 }
5417 return false;
5418 }
5419
5420 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
5421 return StmtVisitorTy::Visit(EvalExpr);
5422 }
5423
5424protected:
5425 EvalInfo &Info;
5426 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
5427 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
5428
5429 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5430 return Info.CCEDiag(E, D);
5431 }
5432
5433 bool ZeroInitialization(const Expr *E) { return Error(E); }
5434
5435public:
5436 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
5437
5438 EvalInfo &getEvalInfo() { return Info; }
5439
5440 /// Report an evaluation error. This should only be called when an error is
5441 /// first discovered. When propagating an error, just return false.
5442 bool Error(const Expr *E, diag::kind D) {
5443 Info.FFDiag(E, D);
5444 return false;
5445 }
5446 bool Error(const Expr *E) {
5447 return Error(E, diag::note_invalid_subexpr_in_const_expr);
5448 }
5449
5450 bool VisitStmt(const Stmt *) {
5451 llvm_unreachable("Expression evaluator should not be called on stmts");
5452 }
5453 bool VisitExpr(const Expr *E) {
5454 return Error(E);
5455 }
5456
5457 bool VisitConstantExpr(const ConstantExpr *E)
5458 { return StmtVisitorTy::Visit(E->getSubExpr()); }
5459 bool VisitParenExpr(const ParenExpr *E)
5460 { return StmtVisitorTy::Visit(E->getSubExpr()); }
5461 bool VisitUnaryExtension(const UnaryOperator *E)
5462 { return StmtVisitorTy::Visit(E->getSubExpr()); }
5463 bool VisitUnaryPlus(const UnaryOperator *E)
5464 { return StmtVisitorTy::Visit(E->getSubExpr()); }
5465 bool VisitChooseExpr(const ChooseExpr *E)
5466 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
5467 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
5468 { return StmtVisitorTy::Visit(E->getResultExpr()); }
5469 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
5470 { return StmtVisitorTy::Visit(E->getReplacement()); }
5471 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
5472 TempVersionRAII RAII(*Info.CurrentCall);
5473 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
5474 return StmtVisitorTy::Visit(E->getExpr());
5475 }
5476 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
5477 TempVersionRAII RAII(*Info.CurrentCall);
5478 // The initializer may not have been parsed yet, or might be erroneous.
5479 if (!E->getExpr())
5480 return Error(E);
5481 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
5482 return StmtVisitorTy::Visit(E->getExpr());
5483 }
5484
5485 // We cannot create any objects for which cleanups are required, so there is
5486 // nothing to do here; all cleanups must come from unevaluated subexpressions.
5487 bool VisitExprWithCleanups(const ExprWithCleanups *E)
5488 { return StmtVisitorTy::Visit(E->getSubExpr()); }
5489
5490 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
5491 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
5492 return static_cast<Derived*>(this)->VisitCastExpr(E);
5493 }
5494 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
5495 if (!Info.Ctx.getLangOpts().CPlusPlus2a)
5496 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
5497 return static_cast<Derived*>(this)->VisitCastExpr(E);
5498 }
5499
5500 bool VisitBinaryOperator(const BinaryOperator *E) {
5501 switch (E->getOpcode()) {
5502 default:
5503 return Error(E);
5504
5505 case BO_Comma:
5506 VisitIgnoredValue(E->getLHS());
5507 return StmtVisitorTy::Visit(E->getRHS());
5508
5509 case BO_PtrMemD:
5510 case BO_PtrMemI: {
5511 LValue Obj;
5512 if (!HandleMemberPointerAccess(Info, E, Obj))
5513 return false;
5514 APValue Result;
5515 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
5516 return false;
5517 return DerivedSuccess(Result, E);
5518 }
5519 }
5520 }
5521
5522 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
5523 // Evaluate and cache the common expression. We treat it as a temporary,
5524 // even though it's not quite the same thing.
5525 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
5526 Info, E->getCommon()))
5527 return false;
5528
5529 return HandleConditionalOperator(E);
5530 }
5531
5532 bool VisitConditionalOperator(const ConditionalOperator *E) {
5533 bool IsBcpCall = false;
5534 // If the condition (ignoring parens) is a __builtin_constant_p call,
5535 // the result is a constant expression if it can be folded without
5536 // side-effects. This is an important GNU extension. See GCC PR38377
5537 // for discussion.
5538 if (const CallExpr *CallCE =
5539 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
5540 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
5541 IsBcpCall = true;
5542
5543 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
5544 // constant expression; we can't check whether it's potentially foldable.
5545 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
5546 return false;
5547
5548 FoldConstant Fold(Info, IsBcpCall);
5549 if (!HandleConditionalOperator(E)) {
5550 Fold.keepDiagnostics();
5551 return false;
5552 }
5553
5554 return true;
5555 }
5556
5557 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
5558 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
5559 return DerivedSuccess(*Value, E);
5560
5561 const Expr *Source = E->getSourceExpr();
5562 if (!Source)
5563 return Error(E);
5564 if (Source == E) { // sanity checking.
5565 assert(0 && "OpaqueValueExpr recursively refers to itself");
5566 return Error(E);
5567 }
5568 return StmtVisitorTy::Visit(Source);
5569 }
5570
5571 bool VisitCallExpr(const CallExpr *E) {
5572 APValue Result;
5573 if (!handleCallExpr(E, Result, nullptr))
5574 return false;
5575 return DerivedSuccess(Result, E);
5576 }
5577
5578 bool handleCallExpr(const CallExpr *E, APValue &Result,
5579 const LValue *ResultSlot) {
5580 const Expr *Callee = E->getCallee()->IgnoreParens();
5581 QualType CalleeType = Callee->getType();
5582
5583 const FunctionDecl *FD = nullptr;
5584 LValue *This = nullptr, ThisVal;
5585 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
5586 bool HasQualifier = false;
5587
5588 // Extract function decl and 'this' pointer from the callee.
5589 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
5590 const CXXMethodDecl *Member = nullptr;
5591 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
5592 // Explicit bound member calls, such as x.f() or p->g();
5593 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
5594 return false;
5595 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
5596 if (!Member)
5597 return Error(Callee);
5598 This = &ThisVal;
5599 HasQualifier = ME->hasQualifier();
5600 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
5601 // Indirect bound member calls ('.*' or '->*').
5602 Member = dyn_cast_or_null<CXXMethodDecl>(
5603 HandleMemberPointerAccess(Info, BE, ThisVal, false));
5604 if (!Member)
5605 return Error(Callee);
5606 This = &ThisVal;
5607 } else
5608 return Error(Callee);
5609 FD = Member;
5610 } else if (CalleeType->isFunctionPointerType()) {
5611 LValue Call;
5612 if (!EvaluatePointer(Callee, Call, Info))
5613 return false;
5614
5615 if (!Call.getLValueOffset().isZero())
5616 return Error(Callee);
5617 FD = dyn_cast_or_null<FunctionDecl>(
5618 Call.getLValueBase().dyn_cast<const ValueDecl*>());
5619 if (!FD)
5620 return Error(Callee);
5621 // Don't call function pointers which have been cast to some other type.
5622 // Per DR (no number yet), the caller and callee can differ in noexcept.
5623 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
5624 CalleeType->getPointeeType(), FD->getType())) {
5625 return Error(E);
5626 }
5627
5628 // Overloaded operator calls to member functions are represented as normal
5629 // calls with '*this' as the first argument.
5630 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
5631 if (MD && !MD->isStatic()) {
5632 // FIXME: When selecting an implicit conversion for an overloaded
5633 // operator delete, we sometimes try to evaluate calls to conversion
5634 // operators without a 'this' parameter!
5635 if (Args.empty())
5636 return Error(E);
5637
5638 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
5639 return false;
5640 This = &ThisVal;
5641 Args = Args.slice(1);
5642 } else if (MD && MD->isLambdaStaticInvoker()) {
5643 // Map the static invoker for the lambda back to the call operator.
5644 // Conveniently, we don't have to slice out the 'this' argument (as is
5645 // being done for the non-static case), since a static member function
5646 // doesn't have an implicit argument passed in.
5647 const CXXRecordDecl *ClosureClass = MD->getParent();
5648 assert(
5649 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
5650 "Number of captures must be zero for conversion to function-ptr");
5651
5652 const CXXMethodDecl *LambdaCallOp =
5653 ClosureClass->getLambdaCallOperator();
5654
5655 // Set 'FD', the function that will be called below, to the call
5656 // operator. If the closure object represents a generic lambda, find
5657 // the corresponding specialization of the call operator.
5658
5659 if (ClosureClass->isGenericLambda()) {
5660 assert(MD->isFunctionTemplateSpecialization() &&
5661 "A generic lambda's static-invoker function must be a "
5662 "template specialization");
5663 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
5664 FunctionTemplateDecl *CallOpTemplate =
5665 LambdaCallOp->getDescribedFunctionTemplate();
5666 void *InsertPos = nullptr;
5667 FunctionDecl *CorrespondingCallOpSpecialization =
5668 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
5669 assert(CorrespondingCallOpSpecialization &&
5670 "We must always have a function call operator specialization "
5671 "that corresponds to our static invoker specialization");
5672 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
5673 } else
5674 FD = LambdaCallOp;
5675 }
5676 } else
5677 return Error(E);
5678
5679 SmallVector<QualType, 4> CovariantAdjustmentPath;
5680 if (This) {
5681 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
5682 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
5683 // Perform virtual dispatch, if necessary.
5684 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
5685 CovariantAdjustmentPath);
5686 if (!FD)
5687 return false;
5688 } else {
5689 // Check that the 'this' pointer points to an object of the right type.
5690 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
5691 return false;
5692 }
5693 }
5694
5695 const FunctionDecl *Definition = nullptr;
5696 Stmt *Body = FD->getBody(Definition);
5697
5698 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
5699 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
5700 Result, ResultSlot))
5701 return false;
5702
5703 if (!CovariantAdjustmentPath.empty() &&
5704 !HandleCovariantReturnAdjustment(Info, E, Result,
5705 CovariantAdjustmentPath))
5706 return false;
5707
5708 return true;
5709 }
5710
5711 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5712 return StmtVisitorTy::Visit(E->getInitializer());
5713 }
5714 bool VisitInitListExpr(const InitListExpr *E) {
5715 if (E->getNumInits() == 0)
5716 return DerivedZeroInitialization(E);
5717 if (E->getNumInits() == 1)
5718 return StmtVisitorTy::Visit(E->getInit(0));
5719 return Error(E);
5720 }
5721 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
5722 return DerivedZeroInitialization(E);
5723 }
5724 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
5725 return DerivedZeroInitialization(E);
5726 }
5727 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
5728 return DerivedZeroInitialization(E);
5729 }
5730
5731 /// A member expression where the object is a prvalue is itself a prvalue.
5732 bool VisitMemberExpr(const MemberExpr *E) {
5733 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
5734 "missing temporary materialization conversion");
5735 assert(!E->isArrow() && "missing call to bound member function?");
5736
5737 APValue Val;
5738 if (!Evaluate(Val, Info, E->getBase()))
5739 return false;
5740
5741 QualType BaseTy = E->getBase()->getType();
5742
5743 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
5744 if (!FD) return Error(E);
5745 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
5746 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5747 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5748
5749 // Note: there is no lvalue base here. But this case should only ever
5750 // happen in C or in C++98, where we cannot be evaluating a constexpr
5751 // constructor, which is the only case the base matters.
5752 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
5753 SubobjectDesignator Designator(BaseTy);
5754 Designator.addDeclUnchecked(FD);
5755
5756 APValue Result;
5757 return extractSubobject(Info, E, Obj, Designator, Result) &&
5758 DerivedSuccess(Result, E);
5759 }
5760
5761 bool VisitCastExpr(const CastExpr *E) {
5762 switch (E->getCastKind()) {
5763 default:
5764 break;
5765
5766 case CK_AtomicToNonAtomic: {
5767 APValue AtomicVal;
5768 // This does not need to be done in place even for class/array types:
5769 // atomic-to-non-atomic conversion implies copying the object
5770 // representation.
5771 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
5772 return false;
5773 return DerivedSuccess(AtomicVal, E);
5774 }
5775
5776 case CK_NoOp:
5777 case CK_UserDefinedConversion:
5778 return StmtVisitorTy::Visit(E->getSubExpr());
5779
5780 case CK_LValueToRValue: {
5781 const Expr *SubExpr = E->getSubExpr();
5782 LValue LVal;
5783 if (!EvaluateLValue(SubExpr, LVal, Info))
5784 return false;
5785 APValue RVal;
5786 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5787 if (!handleLValueToRValueConversion(Info, E, SubExpr->getType(),
5788 LVal, RVal))
5789 return false;
5790
5791 // CHERI: If the LValue is a capability with an integer initializer, then
5792 // extract the int value.
5793 if (SubExpr->getType()->isIntCapType()) {
5794 Expr::EvalResult ExprResult;
5795 if (!SubExpr->EvaluateAsInt(ExprResult, Info.Ctx))
5796 return false;
5797 ExprResult.Val.getInt().setIsUnsigned(SubExpr->getType()->isUnsignedIntegerOrEnumerationType());
5798 RVal = ExprResult.Val;
5799 }
5800 return DerivedSuccess(RVal, E);
5801 }
5802 }
5803
5804 return Error(E);
5805 }
5806
5807 bool VisitUnaryPostInc(const UnaryOperator *UO) {
5808 return VisitUnaryPostIncDec(UO);
5809 }
5810 bool VisitUnaryPostDec(const UnaryOperator *UO) {
5811 return VisitUnaryPostIncDec(UO);
5812 }
5813 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
5814 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5815 return Error(UO);
5816
5817 LValue LVal;
5818 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5819 return false;
5820 APValue RVal;
5821 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5822 UO->isIncrementOp(), &RVal))
5823 return false;
5824 return DerivedSuccess(RVal, UO);
5825 }
5826
5827 bool VisitStmtExpr(const StmtExpr *E) {
5828 // We will have checked the full-expressions inside the statement expression
5829 // when they were completed, and don't need to check them again now.
5830 if (Info.checkingForOverflow())
5831 return Error(E);
5832
5833 BlockScopeRAII Scope(Info);
5834 const CompoundStmt *CS = E->getSubStmt();
5835 if (CS->body_empty())
5836 return true;
5837
5838 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5839 BE = CS->body_end();
5840 /**/; ++BI) {
5841 if (BI + 1 == BE) {
5842 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5843 if (!FinalExpr) {
5844 Info.FFDiag((*BI)->getBeginLoc(),
5845 diag::note_constexpr_stmt_expr_unsupported);
5846 return false;
5847 }
5848 return this->Visit(FinalExpr);
5849 }
5850
5851 APValue ReturnValue;
5852 StmtResult Result = { ReturnValue, nullptr };
5853 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
5854 if (ESR != ESR_Succeeded) {
5855 // FIXME: If the statement-expression terminated due to 'return',
5856 // 'break', or 'continue', it would be nice to propagate that to
5857 // the outer statement evaluation rather than bailing out.
5858 if (ESR != ESR_Failed)
5859 Info.FFDiag((*BI)->getBeginLoc(),
5860 diag::note_constexpr_stmt_expr_unsupported);
5861 return false;
5862 }
5863 }
5864
5865 llvm_unreachable("Return from function from the loop above.");
5866 }
5867
5868 /// Visit a value which is evaluated, but whose value is ignored.
5869 void VisitIgnoredValue(const Expr *E) {
5870 EvaluateIgnoredValue(Info, E);
5871 }
5872
5873 /// Potentially visit a MemberExpr's base expression.
5874 void VisitIgnoredBaseExpression(const Expr *E) {
5875 // While MSVC doesn't evaluate the base expression, it does diagnose the
5876 // presence of side-effecting behavior.
5877 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5878 return;
5879 VisitIgnoredValue(E);
5880 }
5881};
5882
5883} // namespace
5884
5885//===----------------------------------------------------------------------===//
5886// Common base class for lvalue and temporary evaluation.
5887//===----------------------------------------------------------------------===//
5888namespace {
5889template<class Derived>
5890class LValueExprEvaluatorBase
5891 : public ExprEvaluatorBase<Derived> {
5892protected:
5893 LValue &Result;
5894 bool InvalidBaseOK;
5895 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
5896 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
5897
5898 bool Success(APValue::LValueBase B) {
5899 Result.set(B);
5900 return true;
5901 }
5902
5903 bool evaluatePointer(const Expr *E, LValue &Result) {
5904 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5905 }
5906
5907public:
5908 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5909 : ExprEvaluatorBaseTy(Info), Result(Result),
5910 InvalidBaseOK(InvalidBaseOK) {}
5911
5912 bool Success(const APValue &V, const Expr *E) {
5913 Result.setFrom(this->Info.Ctx, V);
5914 return true;
5915 }
5916
5917 bool VisitMemberExpr(const MemberExpr *E) {
5918 // Handle non-static data members.
5919 QualType BaseTy;
5920 bool EvalOK;
5921 if (E->isArrow()) {
5922 EvalOK = evaluatePointer(E->getBase(), Result);
5923 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
5924 } else if (E->getBase()->isRValue()) {
5925 assert(E->getBase()->getType()->isRecordType());
5926 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
5927 BaseTy = E->getBase()->getType();
5928 } else {
5929 EvalOK = this->Visit(E->getBase());
5930 BaseTy = E->getBase()->getType();
5931 }
5932 if (!EvalOK) {
5933 if (!InvalidBaseOK)
5934 return false;
5935 Result.setInvalid(E);
5936 return true;
5937 }
5938
5939 const ValueDecl *MD = E->getMemberDecl();
5940 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5941 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5942 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5943 (void)BaseTy;
5944 if (!HandleLValueMember(this->Info, E, Result, FD))
5945 return false;
5946 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
5947 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5948 return false;
5949 } else
5950 return this->Error(E);
5951
5952 if (MD->getType()->isReferenceType()) {
5953 APValue RefValue;
5954 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
5955 RefValue))
5956 return false;
5957 return Success(RefValue, E);
5958 }
5959 return true;
5960 }
5961
5962 bool VisitBinaryOperator(const BinaryOperator *E) {
5963 switch (E->getOpcode()) {
5964 default:
5965 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5966
5967 case BO_PtrMemD:
5968 case BO_PtrMemI:
5969 return HandleMemberPointerAccess(this->Info, E, Result);
5970 }
5971 }
5972
5973 bool VisitCastExpr(const CastExpr *E) {
5974 switch (E->getCastKind()) {
5975 default:
5976 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5977
5978 case CK_DerivedToBase:
5979 case CK_UncheckedDerivedToBase:
5980 if (!this->Visit(E->getSubExpr()))
5981 return false;
5982
5983 // Now figure out the necessary offset to add to the base LV to get from
5984 // the derived class to the base class.
5985 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5986 Result);
5987 }
5988 }
5989};
5990}
5991
5992//===----------------------------------------------------------------------===//
5993// LValue Evaluation
5994//
5995// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5996// function designators (in C), decl references to void objects (in C), and
5997// temporaries (if building with -Wno-address-of-temporary).
5998//
5999// LValue evaluation produces values comprising a base expression of one of the
6000// following types:
6001// - Declarations
6002// * VarDecl
6003// * FunctionDecl
6004// - Literals
6005// * CompoundLiteralExpr in C (and in global scope in C++)
6006// * StringLiteral
6007// * PredefinedExpr
6008// * ObjCStringLiteralExpr
6009// * ObjCEncodeExpr
6010// * AddrLabelExpr
6011// * BlockExpr
6012// * CallExpr for a MakeStringConstant builtin
6013// - typeid(T) expressions, as TypeInfoLValues
6014// - Locals and temporaries
6015// * MaterializeTemporaryExpr
6016// * Any Expr, with a CallIndex indicating the function in which the temporary
6017// was evaluated, for cases where the MaterializeTemporaryExpr is missing
6018// from the AST (FIXME).
6019// * A MaterializeTemporaryExpr that has static storage duration, with no
6020// CallIndex, for a lifetime-extended temporary.
6021// plus an offset in bytes.
6022//===----------------------------------------------------------------------===//
6023namespace {
6024class LValueExprEvaluator
6025 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
6026public:
6027 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
6028 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
6029
6030 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
6031 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
6032
6033 bool VisitDeclRefExpr(const DeclRefExpr *E);
6034 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
6035 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
6036 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
6037 bool VisitMemberExpr(const MemberExpr *E);
6038 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
6039 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
6040 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
6041 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
6042 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
6043 bool VisitUnaryDeref(const UnaryOperator *E);
6044 bool VisitUnaryReal(const UnaryOperator *E);
6045 bool VisitUnaryImag(const UnaryOperator *E);
6046 bool VisitUnaryPreInc(const UnaryOperator *UO) {
6047 return VisitUnaryPreIncDec(UO);
6048 }
6049 bool VisitUnaryPreDec(const UnaryOperator *UO) {
6050 return VisitUnaryPreIncDec(UO);
6051 }
6052 bool VisitBinAssign(const BinaryOperator *BO);
6053 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
6054
6055 bool VisitCastExpr(const CastExpr *E) {
6056 switch (E->getCastKind()) {
6057 default:
6058 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6059
6060 case CK_LValueBitCast:
6061 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6062 if (!Visit(E->getSubExpr()))
6063 return false;
6064 Result.Designator.setInvalid();
6065 return true;
6066
6067 case CK_BaseToDerived:
6068 if (!Visit(E->getSubExpr()))
6069 return false;
6070 return HandleBaseToDerivedCast(Info, E, Result);
6071
6072 case CK_Dynamic:
6073 if (!Visit(E->getSubExpr()))
6074 return false;
6075 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
6076 }
6077 }
6078};
6079} // end anonymous namespace
6080
6081/// Evaluate an expression as an lvalue. This can be legitimately called on
6082/// expressions which are not glvalues, in three cases:
6083/// * function designators in C, and
6084/// * "extern void" objects
6085/// * @selector() expressions in Objective-C
6086static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
6087 bool InvalidBaseOK) {
6088 assert(E->isGLValue() || E->getType()->isFunctionType() ||
6089 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
6090 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
6091}
6092
6093bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
6094 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
6095 return Success(FD);
6096 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
6097 return VisitVarDecl(E, VD);
6098 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
6099 return Visit(BD->getBinding());
6100 return Error(E);
6101}
6102
6103
6104bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
6105
6106 // If we are within a lambda's call operator, check whether the 'VD' referred
6107 // to within 'E' actually represents a lambda-capture that maps to a
6108 // data-member/field within the closure object, and if so, evaluate to the
6109 // field or what the field refers to.
6110 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
6111 isa<DeclRefExpr>(E) &&
6112 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
6113 // We don't always have a complete capture-map when checking or inferring if
6114 // the function call operator meets the requirements of a constexpr function
6115 // - but we don't need to evaluate the captures to determine constexprness
6116 // (dcl.constexpr C++17).
6117 if (Info.checkingPotentialConstantExpression())
6118 return false;
6119
6120 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
6121 // Start with 'Result' referring to the complete closure object...
6122 Result = *Info.CurrentCall->This;
6123 // ... then update it to refer to the field of the closure object
6124 // that represents the capture.
6125 if (!HandleLValueMember(Info, E, Result, FD))
6126 return false;
6127 // And if the field is of reference type, update 'Result' to refer to what
6128 // the field refers to.
6129 if (FD->getType()->isReferenceType()) {
6130 APValue RVal;
6131 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
6132 RVal))
6133 return false;
6134 Result.setFrom(Info.Ctx, RVal);
6135 }
6136 return true;
6137 }
6138 }
6139 CallStackFrame *Frame = nullptr;
6140 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
6141 // Only if a local variable was declared in the function currently being
6142 // evaluated, do we expect to be able to find its value in the current
6143 // frame. (Otherwise it was likely declared in an enclosing context and
6144 // could either have a valid evaluatable value (for e.g. a constexpr
6145 // variable) or be ill-formed (and trigger an appropriate evaluation
6146 // diagnostic)).
6147 if (Info.CurrentCall->Callee &&
6148 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
6149 Frame = Info.CurrentCall;
6150 }
6151 }
6152
6153 if (!VD->getType()->isReferenceType()) {
6154 if (Frame) {
6155 Result.set({VD, Frame->Index,
6156 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
6157 return true;
6158 }
6159 return Success(VD);
6160 }
6161
6162 APValue *V;
6163 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
6164 return false;
6165 if (!V->hasValue()) {
6166 // FIXME: Is it possible for V to be indeterminate here? If so, we should
6167 // adjust the diagnostic to say that.
6168 if (!Info.checkingPotentialConstantExpression())
6169 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
6170 return false;
6171 }
6172 return Success(*V, E);
6173}
6174
6175bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
6176 const MaterializeTemporaryExpr *E) {
6177 // Walk through the expression to find the materialized temporary itself.
6178 SmallVector<const Expr *, 2> CommaLHSs;
6179 SmallVector<SubobjectAdjustment, 2> Adjustments;
6180 const Expr *Inner = E->GetTemporaryExpr()->
6181 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
6182
6183 // If we passed any comma operators, evaluate their LHSs.
6184 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
6185 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
6186 return false;
6187
6188 // A materialized temporary with static storage duration can appear within the
6189 // result of a constant expression evaluation, so we need to preserve its
6190 // value for use outside this evaluation.
6191 APValue *Value;
6192 if (E->getStorageDuration() == SD_Static) {
6193 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
6194 *Value = APValue();
6195 Result.set(E);
6196 } else {
6197 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
6198 *Info.CurrentCall);
6199 }
6200
6201 QualType Type = Inner->getType();
6202
6203 // Materialize the temporary itself.
6204 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
6205 (E->getStorageDuration() == SD_Static &&
6206 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
6207 *Value = APValue();
6208 return false;
6209 }
6210
6211 // Adjust our lvalue to refer to the desired subobject.
6212 for (unsigned I = Adjustments.size(); I != 0; /**/) {
6213 --I;
6214 switch (Adjustments[I].Kind) {
6215 case SubobjectAdjustment::DerivedToBaseAdjustment:
6216 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
6217 Type, Result))
6218 return false;
6219 Type = Adjustments[I].DerivedToBase.BasePath->getType();
6220 break;
6221
6222 case SubobjectAdjustment::FieldAdjustment:
6223 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
6224 return false;
6225 Type = Adjustments[I].Field->getType();
6226 break;
6227
6228 case SubobjectAdjustment::MemberPointerAdjustment:
6229 if (!HandleMemberPointerAccess(this->Info, Type, Result,
6230 Adjustments[I].Ptr.RHS))
6231 return false;
6232 Type = Adjustments[I].Ptr.MPT->getPointeeType();
6233 break;
6234 }
6235 }
6236
6237 return true;
6238}
6239
6240bool
6241LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
6242 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
6243 "lvalue compound literal in c++?");
6244 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
6245 // only see this when folding in C, so there's no standard to follow here.
6246 return Success(E);
6247}
6248
6249bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
6250 TypeInfoLValue TypeInfo;
6251
6252 if (!E->isPotentiallyEvaluated()) {
6253 if (E->isTypeOperand())
6254 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
6255 else
6256 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
6257 } else {
6258 if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
6259 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
6260 << E->getExprOperand()->getType()
6261 << E->getExprOperand()->getSourceRange();
6262 }
6263
6264 if (!Visit(E->getExprOperand()))
6265 return false;
6266
6267 Optional<DynamicType> DynType =
6268 ComputeDynamicType(Info, E, Result, AK_TypeId);
6269 if (!DynType)
6270 return false;
6271
6272 TypeInfo =
6273 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
6274 }
6275
6276 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
6277}
6278
6279bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
6280 return Success(E);
6281}
6282
6283bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
6284 // Handle static data members.
6285 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
6286 VisitIgnoredBaseExpression(E->getBase());
6287 return VisitVarDecl(E, VD);
6288 }
6289
6290 // Handle static member functions.
6291 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
6292 if (MD->isStatic()) {
6293 VisitIgnoredBaseExpression(E->getBase());
6294 return Success(MD);
6295 }
6296 }
6297
6298 // Handle non-static data members.
6299 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
6300}
6301
6302bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
6303 // FIXME: Deal with vectors as array subscript bases.
6304 if (E->getBase()->getType()->isVectorType())
6305 return Error(E);
6306
6307 bool Success = true;
6308 if (!evaluatePointer(E->getBase(), Result)) {
6309 if (!Info.noteFailure())
6310 return false;
6311 Success = false;
6312 }
6313
6314 APSInt Index;
6315 if (!EvaluateInteger(E->getIdx(), Index, Info))
6316 return false;
6317
6318 return Success &&
6319 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
6320}
6321
6322bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
6323 return evaluatePointer(E->getSubExpr(), Result);
6324}
6325
6326bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6327 if (!Visit(E->getSubExpr()))
6328 return false;
6329 // __real is a no-op on scalar lvalues.
6330 if (E->getSubExpr()->getType()->isAnyComplexType())
6331 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
6332 return true;
6333}
6334
6335bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6336 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
6337 "lvalue __imag__ on scalar?");
6338 if (!Visit(E->getSubExpr()))
6339 return false;
6340 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
6341 return true;
6342}
6343
6344bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
6345 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6346 return Error(UO);
6347
6348 if (!this->Visit(UO->getSubExpr()))
6349 return false;
6350
6351 return handleIncDec(
6352 this->Info, UO, Result, UO->getSubExpr()->getType(),
6353 UO->isIncrementOp(), nullptr);
6354}
6355
6356bool LValueExprEvaluator::VisitCompoundAssignOperator(
6357 const CompoundAssignOperator *CAO) {
6358 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6359 return Error(CAO);
6360
6361 APValue RHS;
6362
6363 // The overall lvalue result is the result of evaluating the LHS.
6364 if (!this->Visit(CAO->getLHS())) {
6365 if (Info.noteFailure())
6366 Evaluate(RHS, this->Info, CAO->getRHS());
6367 return false;
6368 }
6369
6370 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
6371 return false;
6372
6373 return handleCompoundAssignment(
6374 this->Info, CAO,
6375 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
6376 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
6377}
6378
6379bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
6380 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6381 return Error(E);
6382
6383 APValue NewVal;
6384
6385 if (!this->Visit(E->getLHS())) {
6386 if (Info.noteFailure())
6387 Evaluate(NewVal, this->Info, E->getRHS());
6388 return false;
6389 }
6390
6391 if (!Evaluate(NewVal, this->Info, E->getRHS()))
6392 return false;
6393
6394 if (Info.getLangOpts().CPlusPlus2a &&
6395 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
6396 return false;
6397
6398 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
6399 NewVal);
6400}
6401
6402//===----------------------------------------------------------------------===//
6403// Pointer Evaluation
6404//===----------------------------------------------------------------------===//
6405
6406/// Attempts to compute the number of bytes available at the pointer
6407/// returned by a function with the alloc_size attribute. Returns true if we
6408/// were successful. Places an unsigned number into `Result`.
6409///
6410/// This expects the given CallExpr to be a call to a function with an
6411/// alloc_size attribute.
6412static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6413 const CallExpr *Call,
6414 llvm::APInt &Result) {
6415 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
6416
6417 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
6418 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
6419 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
6420 if (Call->getNumArgs() <= SizeArgNo)
6421 return false;
6422
6423 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
6424 Expr::EvalResult ExprResult;
6425 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
6426 return false;
6427 Into = ExprResult.Val.getInt();
6428 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
6429 return false;
6430 Into = Into.zextOrSelf(BitsInSizeT);
6431 return true;
6432 };
6433
6434 APSInt SizeOfElem;
6435 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
6436 return false;
6437
6438 if (!AllocSize->getNumElemsParam().isValid()) {
6439 Result = std::move(SizeOfElem);
6440 return true;
6441 }
6442
6443 APSInt NumberOfElems;
6444 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
6445 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
6446 return false;
6447
6448 bool Overflow;
6449 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
6450 if (Overflow)
6451 return false;
6452
6453 Result = std::move(BytesAvailable);
6454 return true;
6455}
6456
6457/// Convenience function. LVal's base must be a call to an alloc_size
6458/// function.
6459static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6460 const LValue &LVal,
6461 llvm::APInt &Result) {
6462 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
6463 "Can't get the size of a non alloc_size function");
6464 const auto *Base = LVal.getLValueBase().get<const Expr *>();
6465 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
6466 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
6467}
6468
6469/// Attempts to evaluate the given LValueBase as the result of a call to
6470/// a function with the alloc_size attribute. If it was possible to do so, this
6471/// function will return true, make Result's Base point to said function call,
6472/// and mark Result's Base as invalid.
6473static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
6474 LValue &Result) {
6475 if (Base.isNull())
6476 return false;
6477
6478 // Because we do no form of static analysis, we only support const variables.
6479 //
6480 // Additionally, we can't support parameters, nor can we support static
6481 // variables (in the latter case, use-before-assign isn't UB; in the former,
6482 // we have no clue what they'll be assigned to).
6483 const auto *VD =
6484 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
6485 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
6486 return false;
6487
6488 const Expr *Init = VD->getAnyInitializer();
6489 if (!Init)
6490 return false;
6491
6492 const Expr *E = Init->IgnoreParens();
6493 if (!tryUnwrapAllocSizeCall(E))
6494 return false;
6495
6496 // Store E instead of E unwrapped so that the type of the LValue's base is
6497 // what the user wanted.
6498 Result.setInvalid(E);
6499
6500 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
6501 Result.addUnsizedArray(Info, E, Pointee);
6502 return true;
6503}
6504
6505namespace {
6506class PointerExprEvaluator
6507 : public ExprEvaluatorBase<PointerExprEvaluator> {
6508 LValue &Result;
6509 bool InvalidBaseOK;
6510
6511 bool Success(const Expr *E) {
6512 Result.set(E);
6513 return true;
6514 }
6515
6516 bool evaluateLValue(const Expr *E, LValue &Result) {
6517 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
6518 }
6519
6520 bool evaluatePointer(const Expr *E, LValue &Result) {
6521 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
6522 }
6523
6524 bool visitNonBuiltinCallExpr(const CallExpr *E);
6525public:
6526
6527 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
6528 : ExprEvaluatorBaseTy(info), Result(Result),
6529 InvalidBaseOK(InvalidBaseOK) {}
6530
6531 bool Success(const APValue &V, const Expr *E) {
6532 Result.setFrom(Info.Ctx, V);
6533 return true;
6534 }
6535 bool ZeroInitialization(const Expr *E) {
6536 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
6537 Result.setNull(E->getType(), TargetVal);
6538 return true;
6539 }
6540
6541 bool VisitBinaryOperator(const BinaryOperator *E);
6542 bool VisitCastExpr(const CastExpr* E);
6543 bool VisitUnaryAddrOf(const UnaryOperator *E);
6544 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
6545 { return Success(E); }
6546 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
6547 if (E->isExpressibleAsConstantInitializer())
6548 return Success(E);
6549 if (Info.noteFailure())
6550 EvaluateIgnoredValue(Info, E->getSubExpr());
6551 return Error(E);
6552 }
6553 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
6554 { return Success(E); }
6555 bool VisitCallExpr(const CallExpr *E);
6556 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
6557 bool VisitBlockExpr(const BlockExpr *E) {
6558 if (!E->getBlockDecl()->hasCaptures())
6559 return Success(E);
6560 return Error(E);
6561 }
6562 bool VisitCXXThisExpr(const CXXThisExpr *E) {
6563 // Can't look at 'this' when checking a potential constant expression.
6564 if (Info.checkingPotentialConstantExpression())
6565 return false;
6566 if (!Info.CurrentCall->This) {
6567 if (Info.getLangOpts().CPlusPlus11)
6568 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
6569 else
6570 Info.FFDiag(E);
6571 return false;
6572 }
6573 Result = *Info.CurrentCall->This;
6574 // If we are inside a lambda's call operator, the 'this' expression refers
6575 // to the enclosing '*this' object (either by value or reference) which is
6576 // either copied into the closure object's field that represents the '*this'
6577 // or refers to '*this'.
6578 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
6579 // Update 'Result' to refer to the data member/field of the closure object
6580 // that represents the '*this' capture.
6581 if (!HandleLValueMember(Info, E, Result,
6582 Info.CurrentCall->LambdaThisCaptureField))
6583 return false;
6584 // If we captured '*this' by reference, replace the field with its referent.
6585 if (Info.CurrentCall->LambdaThisCaptureField->getType()
6586 ->isPointerType()) {
6587 APValue RVal;
6588 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
6589 RVal))
6590 return false;
6591
6592 Result.setFrom(Info.Ctx, RVal);
6593 }
6594 }
6595 return true;
6596 }
6597
6598 bool VisitSourceLocExpr(const SourceLocExpr *E) {
6599 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
6600 APValue LValResult = E->EvaluateInContext(
6601 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
6602 Result.setFrom(Info.Ctx, LValResult);
6603 return true;
6604 }
6605
6606 // FIXME: Missing: @protocol, @selector
6607};
6608} // end anonymous namespace
6609
6610static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
6611 bool InvalidBaseOK) {
6612 assert(E->isRValue() &&
6613 (E->getType()->hasPointerRepresentation() ||
6614 E->getType()->isCHERICapabilityType(Info.Ctx, false)));
6615 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
6616}
6617
6618bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6619 if (E->getOpcode() != BO_Add &&
6620 E->getOpcode() != BO_Sub)
6621 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6622
6623 const Expr *PExp = E->getLHS();
6624 const Expr *IExp = E->getRHS();
6625 if (IExp->getType()->isPointerType())
6626 std::swap(PExp, IExp);
6627
6628 bool EvalPtrOK = evaluatePointer(PExp, Result);
6629 if (!EvalPtrOK && !Info.noteFailure())
6630 return false;
6631
6632 llvm::APSInt Offset;
6633 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
6634 return false;
6635
6636 if (E->getOpcode() == BO_Sub)
6637 negateAsSigned(Offset);
6638
6639 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
6640 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
6641}
6642
6643bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6644 return evaluateLValue(E->getSubExpr(), Result);
6645}
6646
6647bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6648 const Expr *SubExpr = E->getSubExpr();
6649
6650 switch (E->getCastKind()) {
6651 default:
6652 break;
6653
6654 case CK_BitCast:
6655 case CK_CPointerToObjCPointerCast:
6656 case CK_BlockPointerToObjCPointerCast:
6657 case CK_AnyPointerToBlockPointerCast:
6658 case CK_CHERICapabilityToPointer:
6659 case CK_PointerToCHERICapability:
6660 case CK_AddressSpaceConversion:
6661 if (!Visit(SubExpr))
6662 return false;
6663 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
6664 // permitted in constant expressions in C++11. Bitcasts from cv void* are
6665 // also static_casts, but we disallow them as a resolution to DR1312.
6666 if (!E->getType()->isVoidPointerType()) {
6667 Result.Designator.setInvalid();
6668 if (SubExpr->getType()->isVoidPointerType())
6669 CCEDiag(E, diag::note_constexpr_invalid_cast)
6670 << 3 << SubExpr->getType();
6671 else
6672 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6673 }
6674 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
6675 ZeroInitialization(E);
6676 return true;
6677
6678 case CK_DerivedToBase:
6679 case CK_UncheckedDerivedToBase:
6680 if (!evaluatePointer(E->getSubExpr(), Result))
6681 return false;
6682 if (!Result.Base && Result.Offset.isZero())
6683 return true;
6684
6685 // Now figure out the necessary offset to add to the base LV to get from
6686 // the derived class to the base class.
6687 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
6688 castAs<PointerType>()->getPointeeType(),
6689 Result);
6690
6691 case CK_BaseToDerived:
6692 if (!Visit(E->getSubExpr()))
6693 return false;
6694 if (!Result.Base && Result.Offset.isZero())
6695 return true;
6696 return HandleBaseToDerivedCast(Info, E, Result);
6697
6698 case CK_Dynamic:
6699 if (!Visit(E->getSubExpr()))
6700 return false;
6701 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
6702
6703 case CK_NullToPointer:
6704 VisitIgnoredValue(E->getSubExpr());
6705 return ZeroInitialization(E);
6706
6707 case CK_IntegralCast:
6708 if (!E->getType()->isCHERICapabilityType(Info.Ctx))
6709 return false;
6710 LLVM_FALLTHROUGH;
6711 case CK_IntegralToPointer: {
6712 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6713
6714 APValue Value;
6715 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
6716 break;
6717
6718 if (Value.isInt()) {
6719 unsigned Size = E->getType()->isCHERICapabilityType(Info.Ctx) ?
6720 Info.Ctx.getTargetInfo().getPointerRangeForCHERICapability() :
6721 Info.Ctx.getIntRange(E->getType());
6722 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
6723 Result.Base = (Expr*)nullptr;
6724 Result.InvalidBase = false;
6725 Result.Offset = CharUnits::fromQuantity(N);
6726 Result.Designator.setInvalid();
6727 Result.IsNullPtr = false;
6728 return true;
6729 } else {
6730 // Cast is of an lvalue, no need to change value.
6731 Result.setFrom(Info.Ctx, Value);
6732 return true;
6733 }
6734 }
6735
6736 case CK_ArrayToPointerDecay: {
6737 if (SubExpr->isGLValue()) {
6738 if (!evaluateLValue(SubExpr, Result))
6739 return false;
6740 } else {
6741 APValue &Value = createTemporary(SubExpr, false, Result,
6742 *Info.CurrentCall);
6743 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
6744 return false;
6745 }
6746 // The result is a pointer to the first element of the array.
6747 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
6748 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
6749 Result.addArray(Info, E, CAT);
6750 else
6751 Result.addUnsizedArray(Info, E, AT->getElementType());
6752 return true;
6753 }
6754
6755 case CK_FunctionToPointerDecay:
6756 return evaluateLValue(SubExpr, Result);
6757
6758 case CK_LValueToRValue: {
6759 LValue LVal;
6760 if (!evaluateLValue(E->getSubExpr(), LVal))
6761 return false;
6762
6763 APValue RVal;
6764 // Note, we use the subexpression's type in order to retain cv-qualifiers.
6765 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
6766 LVal, RVal))
6767 return InvalidBaseOK &&
6768 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
6769 return Success(RVal, E);
6770 }
6771 }
6772
6773 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6774}
6775
6776static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
6777 UnaryExprOrTypeTrait ExprKind) {
6778 // C++ [expr.alignof]p3:
6779 // When alignof is applied to a reference type, the result is the
6780 // alignment of the referenced type.
6781 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6782 T = Ref->getPointeeType();
6783
6784 if (T.getQualifiers().hasUnaligned())
6785 return CharUnits::One();
6786
6787 const bool AlignOfReturnsPreferred =
6788 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
6789
6790 // __alignof is defined to return the preferred alignment.
6791 // Before 8, clang returned the preferred alignment for alignof and _Alignof
6792 // as well.
6793 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
6794 return Info.Ctx.toCharUnitsFromBits(
6795 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
6796 // alignof and _Alignof are defined to return the ABI alignment.
6797 else if (ExprKind == UETT_AlignOf)
6798 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
6799 else
6800 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
6801}
6802
6803static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
6804 UnaryExprOrTypeTrait ExprKind) {
6805 E = E->IgnoreParens();
6806
6807 // The kinds of expressions that we have special-case logic here for
6808 // should be kept up to date with the special checks for those
6809 // expressions in Sema.
6810
6811 // alignof decl is always accepted, even if it doesn't make sense: we default
6812 // to 1 in those cases.
6813 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6814 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6815 /*RefAsPointee*/true);
6816
6817 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
6818 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6819 /*RefAsPointee*/true);
6820
6821 return GetAlignOfType(Info, E->getType(), ExprKind);
6822}
6823
6824// To be clear: this happily visits unsupported builtins. Better name welcomed.
6825bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
6826 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
6827 return true;
6828
6829 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
6830 return false;
6831
6832 Result.setInvalid(E);
6833 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
6834 Result.addUnsizedArray(Info, E, PointeeTy);
6835 return true;
6836}
6837
6838bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
6839 if (IsStringLiteralCall(E))
6840 return Success(E);
6841
6842 if (unsigned BuiltinOp = E->getBuiltinCallee())
6843 return VisitBuiltinCallExpr(E, BuiltinOp);
6844
6845 return visitNonBuiltinCallExpr(E);
6846}
6847
6848bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6849 unsigned BuiltinOp) {
6850 switch (BuiltinOp) {
6851 case Builtin::BI__builtin_addressof:
6852 return evaluateLValue(E->getArg(0), Result);
6853 case Builtin::BI__builtin_assume_aligned_cap:
6854 case Builtin::BI__builtin_assume_aligned: {
6855 // We need to be very careful here because: if the pointer does not have the
6856 // asserted alignment, then the behavior is undefined, and undefined
6857 // behavior is non-constant.
6858 if (!evaluatePointer(E->getArg(0), Result))
6859 return false;
6860
6861 LValue OffsetResult(Result);
6862 APSInt Alignment;
6863 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
6864 return false;
6865 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
6866
6867 if (E->getNumArgs() > 2) {
6868 APSInt Offset;
6869 if (!EvaluateInteger(E->getArg(2), Offset, Info))
6870 return false;
6871
6872 int64_t AdditionalOffset = -Offset.getZExtValue();
6873 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
6874 }
6875
6876 // If there is a base object, then it must have the correct alignment.
6877 if (OffsetResult.Base) {
6878 CharUnits BaseAlignment;
6879 if (const ValueDecl *VD =
6880 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6881 BaseAlignment = Info.Ctx.getDeclAlign(VD);
6882 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
6883 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
6884 } else {
6885 BaseAlignment = GetAlignOfType(
6886 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
6887 }
6888
6889 if (BaseAlignment < Align) {
6890 Result.Designator.setInvalid();
6891 // FIXME: Add support to Diagnostic for long / long long.
6892 CCEDiag(E->getArg(0),
6893 diag::note_constexpr_baa_insufficient_alignment) << 0
6894 << (unsigned)BaseAlignment.getQuantity()
6895 << (unsigned)Align.getQuantity();
6896 return false;
6897 }
6898 }
6899 // TODO: can we handle __builtin_/align_down/aligned_up/is_aligned here?
6900
6901 // The offset must also have the correct alignment.
6902 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
6903 Result.Designator.setInvalid();
6904
6905 (OffsetResult.Base
6906 ? CCEDiag(E->getArg(0),
6907 diag::note_constexpr_baa_insufficient_alignment) << 1
6908 : CCEDiag(E->getArg(0),
6909 diag::note_constexpr_baa_value_insufficient_alignment))
6910 << (int)OffsetResult.Offset.getQuantity()
6911 << (unsigned)Align.getQuantity();
6912 return false;
6913 }
6914
6915 return true;
6916 }
6917 case Builtin::BI__builtin_launder:
6918 return evaluatePointer(E->getArg(0), Result);
6919 case Builtin::BIstrchr:
6920 case Builtin::BIwcschr:
6921 case Builtin::BImemchr:
6922 case Builtin::BIwmemchr:
6923 if (Info.getLangOpts().CPlusPlus11)
6924 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6925 << /*isConstexpr*/0 << /*isConstructor*/0
6926 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6927 else
6928 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6929 LLVM_FALLTHROUGH;
6930 case Builtin::BI__builtin_strchr:
6931 case Builtin::BI__builtin_wcschr:
6932 case Builtin::BI__builtin_memchr:
6933 case Builtin::BI__builtin_char_memchr:
6934 case Builtin::BI__builtin_wmemchr: {
6935 if (!Visit(E->getArg(0)))
6936 return false;
6937 APSInt Desired;
6938 if (!EvaluateInteger(E->getArg(1), Desired, Info))
6939 return false;
6940 uint64_t MaxLength = uint64_t(-1);
6941 if (BuiltinOp != Builtin::BIstrchr &&
6942 BuiltinOp != Builtin::BIwcschr &&
6943 BuiltinOp != Builtin::BI__builtin_strchr &&
6944 BuiltinOp != Builtin::BI__builtin_wcschr) {
6945 APSInt N;
6946 if (!EvaluateInteger(E->getArg(2), N, Info))
6947 return false;
6948 MaxLength = N.getExtValue();
6949 }
6950 // We cannot find the value if there are no candidates to match against.
6951 if (MaxLength == 0u)
6952 return ZeroInitialization(E);
6953 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
6954 Result.Designator.Invalid)
6955 return false;
6956 QualType CharTy = Result.Designator.getType(Info.Ctx);
6957 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
6958 BuiltinOp == Builtin::BI__builtin_memchr;
6959 assert(IsRawByte ||
6960 Info.Ctx.hasSameUnqualifiedType(
6961 CharTy, E->getArg(0)->getType()->getPointeeType()));
6962 // Pointers to const void may point to objects of incomplete type.
6963 if (IsRawByte && CharTy->isIncompleteType()) {
6964 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
6965 return false;
6966 }
6967 // Give up on byte-oriented matching against multibyte elements.
6968 // FIXME: We can compare the bytes in the correct order.
6969 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
6970 return false;
6971 // Figure out what value we're actually looking for (after converting to
6972 // the corresponding unsigned type if necessary).
6973 uint64_t DesiredVal;
6974 bool StopAtNull = false;
6975 switch (BuiltinOp) {
6976 case Builtin::BIstrchr:
6977 case Builtin::BI__builtin_strchr:
6978 // strchr compares directly to the passed integer, and therefore
6979 // always fails if given an int that is not a char.
6980 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6981 E->getArg(1)->getType(),
6982 Desired),
6983 Desired))
6984 return ZeroInitialization(E);
6985 StopAtNull = true;
6986 LLVM_FALLTHROUGH;
6987 case Builtin::BImemchr:
6988 case Builtin::BI__builtin_memchr:
6989 case Builtin::BI__builtin_char_memchr:
6990 // memchr compares by converting both sides to unsigned char. That's also
6991 // correct for strchr if we get this far (to cope with plain char being
6992 // unsigned in the strchr case).
6993 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6994 break;
6995
6996 case Builtin::BIwcschr:
6997 case Builtin::BI__builtin_wcschr:
6998 StopAtNull = true;
6999 LLVM_FALLTHROUGH;
7000 case Builtin::BIwmemchr:
7001 case Builtin::BI__builtin_wmemchr:
7002 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
7003 DesiredVal = Desired.getZExtValue();
7004 break;
7005 }
7006
7007 for (; MaxLength; --MaxLength) {
7008 APValue Char;
7009 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
7010 !Char.isInt())
7011 return false;
7012 if (Char.getInt().getZExtValue() == DesiredVal)
7013 return true;
7014 if (StopAtNull && !Char.getInt())
7015 break;
7016 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
7017 return false;
7018 }
7019 // Not found: return nullptr.
7020 return ZeroInitialization(E);
7021 }
7022
7023 case Builtin::BImemcpy:
7024 case Builtin::BImemmove:
7025 case Builtin::BIwmemcpy:
7026 case Builtin::BIwmemmove:
7027 if (Info.getLangOpts().CPlusPlus11)
7028 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7029 << /*isConstexpr*/0 << /*isConstructor*/0
7030 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7031 else
7032 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7033 LLVM_FALLTHROUGH;
7034 case Builtin::BI__builtin_memcpy:
7035 case Builtin::BI__builtin_memmove:
7036 case Builtin::BI__builtin_wmemcpy:
7037 case Builtin::BI__builtin_wmemmove: {
7038 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
7039 BuiltinOp == Builtin::BIwmemmove ||
7040 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
7041 BuiltinOp == Builtin::BI__builtin_wmemmove;
7042 bool Move = BuiltinOp == Builtin::BImemmove ||
7043 BuiltinOp == Builtin::BIwmemmove ||
7044 BuiltinOp == Builtin::BI__builtin_memmove ||
7045 BuiltinOp == Builtin::BI__builtin_wmemmove;
7046
7047 // The result of mem* is the first argument.
7048 if (!Visit(E->getArg(0)))
7049 return false;
7050 LValue Dest = Result;
7051
7052 LValue Src;
7053 if (!EvaluatePointer(E->getArg(1), Src, Info))
7054 return false;
7055
7056 APSInt N;
7057 if (!EvaluateInteger(E->getArg(2), N, Info))
7058 return false;
7059 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
7060
7061 // If the size is zero, we treat this as always being a valid no-op.
7062 // (Even if one of the src and dest pointers is null.)
7063 if (!N)
7064 return true;
7065
7066 // Otherwise, if either of the operands is null, we can't proceed. Don't
7067 // try to determine the type of the copied objects, because there aren't
7068 // any.
7069 if (!Src.Base || !Dest.Base) {
7070 APValue Val;
7071 (!Src.Base ? Src : Dest).moveInto(Val);
7072 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
7073 << Move << WChar << !!Src.Base
7074 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
7075 return false;
7076 }
7077 if (Src.Designator.Invalid || Dest.Designator.Invalid)
7078 return false;
7079
7080 // We require that Src and Dest are both pointers to arrays of
7081 // trivially-copyable type. (For the wide version, the designator will be
7082 // invalid if the designated object is not a wchar_t.)
7083 QualType T = Dest.Designator.getType(Info.Ctx);
7084 QualType SrcT = Src.Designator.getType(Info.Ctx);
7085 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
7086 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
7087 return false;
7088 }
7089 if (T->isIncompleteType()) {
7090 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
7091 return false;
7092 }
7093 if (!T.isTriviallyCopyableType(Info.Ctx)) {
7094 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
7095 return false;
7096 }
7097
7098 // Figure out how many T's we're copying.
7099 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
7100 if (!WChar) {
7101 uint64_t Remainder;
7102 llvm::APInt OrigN = N;
7103 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
7104 if (Remainder) {
7105 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7106 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
7107 << (unsigned)TSize;
7108 return false;
7109 }
7110 }
7111
7112 // Check that the copying will remain within the arrays, just so that we
7113 // can give a more meaningful diagnostic. This implicitly also checks that
7114 // N fits into 64 bits.
7115 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
7116 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
7117 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
7118 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7119 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
7120 << N.toString(10, /*Signed*/false);
7121 return false;
7122 }
7123 uint64_t NElems = N.getZExtValue();
7124 uint64_t NBytes = NElems * TSize;
7125
7126 // Check for overlap.
7127 int Direction = 1;
7128 if (HasSameBase(Src, Dest)) {
7129 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
7130 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
7131 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
7132 // Dest is inside the source region.
7133 if (!Move) {
7134 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7135 return false;
7136 }
7137 // For memmove and friends, copy backwards.
7138 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
7139 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
7140 return false;
7141 Direction = -1;
7142 } else if (!Move && SrcOffset >= DestOffset &&
7143 SrcOffset - DestOffset < NBytes) {
7144 // Src is inside the destination region for memcpy: invalid.
7145 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7146 return false;
7147 }
7148 }
7149
7150 while (true) {
7151 APValue Val;
7152 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
7153 !handleAssignment(Info, E, Dest, T, Val))
7154 return false;
7155 // Do not iterate past the last element; if we're copying backwards, that
7156 // might take us off the start of the array.
7157 if (--NElems == 0)
7158 return true;
7159 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
7160 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
7161 return false;
7162 }
7163 }
7164
7165 default:
7166 return visitNonBuiltinCallExpr(E);
7167 }
7168}
7169
7170//===----------------------------------------------------------------------===//
7171// Member Pointer Evaluation
7172//===----------------------------------------------------------------------===//
7173
7174namespace {
7175class MemberPointerExprEvaluator
7176 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
7177 MemberPtr &Result;
7178
7179 bool Success(const ValueDecl *D) {
7180 Result = MemberPtr(D);
7181 return true;
7182 }
7183public:
7184
7185 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
7186 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7187
7188 bool Success(const APValue &V, const Expr *E) {
7189 Result.setFrom(V);
7190 return true;
7191 }
7192 bool ZeroInitialization(const Expr *E) {
7193 return Success((const ValueDecl*)nullptr);
7194 }
7195
7196 bool VisitCastExpr(const CastExpr *E);
7197 bool VisitUnaryAddrOf(const UnaryOperator *E);
7198};
7199} // end anonymous namespace
7200
7201static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
7202 EvalInfo &Info) {
7203 assert(E->isRValue() && E->getType()->isMemberPointerType());
7204 return MemberPointerExprEvaluator(Info, Result).Visit(E);
7205}
7206
7207bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7208 switch (E->getCastKind()) {
7209 default:
7210 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7211
7212 case CK_NullToMemberPointer:
7213 VisitIgnoredValue(E->getSubExpr());
7214 return ZeroInitialization(E);
7215
7216 case CK_BaseToDerivedMemberPointer: {
7217 if (!Visit(E->getSubExpr()))
7218 return false;
7219 if (E->path_empty())
7220 return true;
7221 // Base-to-derived member pointer casts store the path in derived-to-base
7222 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
7223 // the wrong end of the derived->base arc, so stagger the path by one class.
7224 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
7225 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
7226 PathI != PathE; ++PathI) {
7227 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7228 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
7229 if (!Result.castToDerived(Derived))
7230 return Error(E);
7231 }
7232 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
7233 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
7234 return Error(E);
7235 return true;
7236 }
7237
7238 case CK_DerivedToBaseMemberPointer:
7239 if (!Visit(E->getSubExpr()))
7240 return false;
7241 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7242 PathE = E->path_end(); PathI != PathE; ++PathI) {
7243 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7244 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7245 if (!Result.castToBase(Base))
7246 return Error(E);
7247 }
7248 return true;
7249 }
7250}
7251
7252bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7253 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7254 // member can be formed.
7255 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
7256}
7257
7258//===----------------------------------------------------------------------===//
7259// Record Evaluation
7260//===----------------------------------------------------------------------===//
7261
7262namespace {
7263 class RecordExprEvaluator
7264 : public ExprEvaluatorBase<RecordExprEvaluator> {
7265 const LValue &This;
7266 APValue &Result;
7267 public:
7268
7269 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
7270 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
7271
7272 bool Success(const APValue &V, const Expr *E) {
7273 Result = V;
7274 return true;
7275 }
7276 bool ZeroInitialization(const Expr *E) {
7277 return ZeroInitialization(E, E->getType());
7278 }
7279 bool ZeroInitialization(const Expr *E, QualType T);
7280
7281 bool VisitCallExpr(const CallExpr *E) {
7282 return handleCallExpr(E, Result, &This);
7283 }
7284 bool VisitCastExpr(const CastExpr *E);
7285 bool VisitInitListExpr(const InitListExpr *E);
7286 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7287 return VisitCXXConstructExpr(E, E->getType());
7288 }
7289 bool VisitLambdaExpr(const LambdaExpr *E);
7290 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
7291 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
7292 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
7293
7294 bool VisitBinCmp(const BinaryOperator *E);
7295 };
7296}
7297
7298/// Perform zero-initialization on an object of non-union class type.
7299/// C++11 [dcl.init]p5:
7300/// To zero-initialize an object or reference of type T means:
7301/// [...]
7302/// -- if T is a (possibly cv-qualified) non-union class type,
7303/// each non-static data member and each base-class subobject is
7304/// zero-initialized
7305static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
7306 const RecordDecl *RD,
7307 const LValue &This, APValue &Result) {
7308 assert(!RD->isUnion() && "Expected non-union class type");
7309 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
7310 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
7311 std::distance(RD->field_begin(), RD->field_end()));
7312
7313 if (RD->isInvalidDecl()) return false;
7314 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7315
7316 if (CD) {
7317 unsigned Index = 0;
7318 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
7319 End = CD->bases_end(); I != End; ++I, ++Index) {
7320 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
7321 LValue Subobject = This;
7322 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
7323 return false;
7324 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
7325 Result.getStructBase(Index)))
7326 return false;
7327 }
7328 }
7329
7330 for (const auto *I : RD->fields()) {
7331 // -- if T is a reference type, no initialization is performed.
7332 if (I->getType()->isReferenceType())
7333 continue;
7334
7335 LValue Subobject = This;
7336 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
7337 return false;
7338
7339 ImplicitValueInitExpr VIE(I->getType());
7340 if (!EvaluateInPlace(
7341 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
7342 return false;
7343 }
7344
7345 return true;
7346}
7347
7348bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
7349 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
7350 if (RD->isInvalidDecl()) return false;
7351 if (RD->isUnion()) {
7352 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
7353 // object's first non-static named data member is zero-initialized
7354 RecordDecl::field_iterator I = RD->field_begin();
7355 if (I == RD->field_end()) {
7356 Result = APValue((const FieldDecl*)nullptr);
7357 return true;
7358 }
7359
7360 LValue Subobject = This;
7361 if (!HandleLValueMember(Info, E, Subobject, *I))
7362 return false;
7363 Result = APValue(*I);
7364 ImplicitValueInitExpr VIE(I->getType());
7365 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
7366 }
7367
7368 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
7369 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
7370 return false;
7371 }
7372
7373 return HandleClassZeroInitialization(Info, E, RD, This, Result);
7374}
7375
7376bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
7377 switch (E->getCastKind()) {
7378 default:
7379 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7380
7381 case CK_ConstructorConversion:
7382 return Visit(E->getSubExpr());
7383
7384 case CK_DerivedToBase:
7385 case CK_UncheckedDerivedToBase: {
7386 APValue DerivedObject;
7387 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
7388 return false;
7389 if (!DerivedObject.isStruct())
7390 return Error(E->getSubExpr());
7391
7392 // Derived-to-base rvalue conversion: just slice off the derived part.
7393 APValue *Value = &DerivedObject;
7394 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
7395 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7396 PathE = E->path_end(); PathI != PathE; ++PathI) {
7397 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
7398 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7399 Value = &Value->getStructBase(getBaseIndex(RD, Base));
7400 RD = Base;
7401 }
7402 Result = *Value;
7403 return true;
7404 }
7405 }
7406}
7407
7408bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7409 if (E->isTransparent())
7410 return Visit(E->getInit(0));
7411
7412 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
7413 if (RD->isInvalidDecl()) return false;
7414 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7415 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
7416
7417 EvalInfo::EvaluatingConstructorRAII EvalObj(
7418 Info,
7419 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7420 CXXRD && CXXRD->getNumBases());
7421
7422 if (RD->isUnion()) {
7423 const FieldDecl *Field = E->getInitializedFieldInUnion();
7424 Result = APValue(Field);
7425 if (!Field)
7426 return true;
7427
7428 // If the initializer list for a union does not contain any elements, the
7429 // first element of the union is value-initialized.
7430 // FIXME: The element should be initialized from an initializer list.
7431 // Is this difference ever observable for initializer lists which
7432 // we don't build?
7433 ImplicitValueInitExpr VIE(Field->getType());
7434 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
7435
7436 LValue Subobject = This;
7437 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
7438 return false;
7439
7440 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7441 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7442 isa<CXXDefaultInitExpr>(InitExpr));
7443
7444 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
7445 }
7446
7447 if (!Result.hasValue())
7448 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
7449 std::distance(RD->field_begin(), RD->field_end()));
7450 unsigned ElementNo = 0;
7451 bool Success = true;
7452
7453 // Initialize base classes.
7454 if (CXXRD && CXXRD->getNumBases()) {
7455 for (const auto &Base : CXXRD->bases()) {
7456 assert(ElementNo < E->getNumInits() && "missing init for base class");
7457 const Expr *Init = E->getInit(ElementNo);
7458
7459 LValue Subobject = This;
7460 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
7461 return false;
7462
7463 APValue &FieldVal = Result.getStructBase(ElementNo);
7464 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
7465 if (!Info.noteFailure())
7466 return false;
7467 Success = false;
7468 }
7469 ++ElementNo;
7470 }
7471
7472 EvalObj.finishedConstructingBases();
7473 }
7474
7475 // Initialize members.
7476 for (const auto *Field : RD->fields()) {
7477 // Anonymous bit-fields are not considered members of the class for
7478 // purposes of aggregate initialization.
7479 if (Field->isUnnamedBitfield())
7480 continue;
7481
7482 LValue Subobject = This;
7483
7484 bool HaveInit = ElementNo < E->getNumInits();
7485
7486 // FIXME: Diagnostics here should point to the end of the initializer
7487 // list, not the start.
7488 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
7489 Subobject, Field, &Layout))
7490 return false;
7491
7492 // Perform an implicit value-initialization for members beyond the end of
7493 // the initializer list.
7494 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
7495 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
7496
7497 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7498 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7499 isa<CXXDefaultInitExpr>(Init));
7500
7501 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7502 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
7503 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
7504 FieldVal, Field))) {
7505 if (!Info.noteFailure())
7506 return false;
7507 Success = false;
7508 }
7509 }
7510
7511 return Success;
7512}
7513
7514bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7515 QualType T) {
7516 // Note that E's type is not necessarily the type of our class here; we might
7517 // be initializing an array element instead.
7518 const CXXConstructorDecl *FD = E->getConstructor();
7519 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
7520
7521 bool ZeroInit = E->requiresZeroInitialization();
7522 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
7523 // If we've already performed zero-initialization, we're already done.
7524 if (Result.hasValue())
7525 return true;
7526
7527 // We can get here in two different ways:
7528 // 1) We're performing value-initialization, and should zero-initialize
7529 // the object, or
7530 // 2) We're performing default-initialization of an object with a trivial
7531 // constexpr default constructor, in which case we should start the
7532 // lifetimes of all the base subobjects (there can be no data member
7533 // subobjects in this case) per [basic.life]p1.
7534 // Either way, ZeroInitialization is appropriate.
7535 return ZeroInitialization(E, T);
7536 }
7537
7538 const FunctionDecl *Definition = nullptr;
7539 auto Body = FD->getBody(Definition);
7540
7541 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
7542 return false;
7543
7544 // Avoid materializing a temporary for an elidable copy/move constructor.
7545 if (E->isElidable() && !ZeroInit)
7546 if (const MaterializeTemporaryExpr *ME
7547 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
7548 return Visit(ME->GetTemporaryExpr());
7549
7550 if (ZeroInit && !ZeroInitialization(E, T))
7551 return false;
7552
7553 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7554 return HandleConstructorCall(E, This, Args,
7555 cast<CXXConstructorDecl>(Definition), Info,
7556 Result);
7557}
7558
7559bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
7560 const CXXInheritedCtorInitExpr *E) {
7561 if (!Info.CurrentCall) {
7562 assert(Info.checkingPotentialConstantExpression());
7563 return false;
7564 }
7565
7566 const CXXConstructorDecl *FD = E->getConstructor();
7567 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
7568 return false;
7569
7570 const FunctionDecl *Definition = nullptr;
7571 auto Body = FD->getBody(Definition);
7572
7573 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
7574 return false;
7575
7576 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
7577 cast<CXXConstructorDecl>(Definition), Info,
7578 Result);
7579}
7580
7581bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
7582 const CXXStdInitializerListExpr *E) {
7583 const ConstantArrayType *ArrayType =
7584 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
7585
7586 LValue Array;
7587 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
7588 return false;
7589
7590 // Get a pointer to the first element of the array.
7591 Array.addArray(Info, E, ArrayType);
7592
7593 // FIXME: Perform the checks on the field types in SemaInit.
7594 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
7595 RecordDecl::field_iterator Field = Record->field_begin();
7596 if (Field == Record->field_end())
7597 return Error(E);
7598
7599 // Start pointer.
7600 if (!Field->getType()->isPointerType() ||
7601 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
7602 ArrayType->getElementType()))
7603 return Error(E);
7604
7605 // FIXME: What if the initializer_list type has base classes, etc?
7606 Result = APValue(APValue::UninitStruct(), 0, 2);
7607 Array.moveInto(Result.getStructField(0));
7608
7609 if (++Field == Record->field_end())
7610 return Error(E);
7611
7612 if (Field->getType()->isPointerType() &&
7613 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
7614 ArrayType->getElementType())) {
7615 // End pointer.
7616 if (!HandleLValueArrayAdjustment(Info, E, Array,
7617 ArrayType->getElementType(),
7618 ArrayType->getSize().getZExtValue()))
7619 return false;
7620 Array.moveInto(Result.getStructField(1));
7621 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
7622 // Length.
7623 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
7624 else
7625 return Error(E);
7626
7627 if (++Field != Record->field_end())
7628 return Error(E);
7629
7630 return true;
7631}
7632
7633bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
7634 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
7635 if (ClosureClass->isInvalidDecl()) return false;
7636
7637 if (Info.checkingPotentialConstantExpression()) return true;
7638
7639 const size_t NumFields =
7640 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
7641
7642 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
7643 E->capture_init_end()) &&
7644 "The number of lambda capture initializers should equal the number of "
7645 "fields within the closure type");
7646
7647 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
7648 // Iterate through all the lambda's closure object's fields and initialize
7649 // them.
7650 auto *CaptureInitIt = E->capture_init_begin();
7651 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
7652 bool Success = true;
7653 for (const auto *Field : ClosureClass->fields()) {
7654 assert(CaptureInitIt != E->capture_init_end());
7655 // Get the initializer for this field
7656 Expr *const CurFieldInit = *CaptureInitIt++;
7657
7658 // If there is no initializer, either this is a VLA or an error has
7659 // occurred.
7660 if (!CurFieldInit)
7661 return Error(E);
7662
7663 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7664 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
7665 if (!Info.keepEvaluatingAfterFailure())
7666 return false;
7667 Success = false;
7668 }
7669 ++CaptureIt;
7670 }
7671 return Success;
7672}
7673
7674static bool EvaluateRecord(const Expr *E, const LValue &This,
7675 APValue &Result, EvalInfo &Info) {
7676 assert(E->isRValue() && E->getType()->isRecordType() &&
7677 "can't evaluate expression as a record rvalue");
7678 return RecordExprEvaluator(Info, This, Result).Visit(E);
7679}
7680
7681//===----------------------------------------------------------------------===//
7682// Temporary Evaluation
7683//
7684// Temporaries are represented in the AST as rvalues, but generally behave like
7685// lvalues. The full-object of which the temporary is a subobject is implicitly
7686// materialized so that a reference can bind to it.
7687//===----------------------------------------------------------------------===//
7688namespace {
7689class TemporaryExprEvaluator
7690 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
7691public:
7692 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
7693 LValueExprEvaluatorBaseTy(Info, Result, false) {}
7694
7695 /// Visit an expression which constructs the value of this temporary.
7696 bool VisitConstructExpr(const Expr *E) {
7697 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
7698 return EvaluateInPlace(Value, Info, Result, E);
7699 }
7700
7701 bool VisitCastExpr(const CastExpr *E) {
7702 switch (E->getCastKind()) {
7703 default:
7704 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7705
7706 case CK_ConstructorConversion:
7707 return VisitConstructExpr(E->getSubExpr());
7708 }
7709 }
7710 bool VisitInitListExpr(const InitListExpr *E) {
7711 return VisitConstructExpr(E);
7712 }
7713 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7714 return VisitConstructExpr(E);
7715 }
7716 bool VisitCallExpr(const CallExpr *E) {
7717 return VisitConstructExpr(E);
7718 }
7719 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
7720 return VisitConstructExpr(E);
7721 }
7722 bool VisitLambdaExpr(const LambdaExpr *E) {
7723 return VisitConstructExpr(E);
7724 }
7725};
7726} // end anonymous namespace
7727
7728/// Evaluate an expression of record type as a temporary.
7729static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
7730 assert(E->isRValue() && E->getType()->isRecordType());
7731 return TemporaryExprEvaluator(Info, Result).Visit(E);
7732}
7733
7734//===----------------------------------------------------------------------===//
7735// Vector Evaluation
7736//===----------------------------------------------------------------------===//
7737
7738namespace {
7739 class VectorExprEvaluator
7740 : public ExprEvaluatorBase<VectorExprEvaluator> {
7741 APValue &Result;
7742 public:
7743
7744 VectorExprEvaluator(EvalInfo &info, APValue &Result)
7745 : ExprEvaluatorBaseTy(info), Result(Result) {}
7746
7747 bool Success(ArrayRef<APValue> V, const Expr *E) {
7748 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
7749 // FIXME: remove this APValue copy.
7750 Result = APValue(V.data(), V.size());
7751 return true;
7752 }
7753 bool Success(const APValue &V, const Expr *E) {
7754 assert(V.isVector());
7755 Result = V;
7756 return true;
7757 }
7758 bool ZeroInitialization(const Expr *E);
7759
7760 bool VisitUnaryReal(const UnaryOperator *E)
7761 { return Visit(E->getSubExpr()); }
7762 bool VisitCastExpr(const CastExpr* E);
7763 bool VisitInitListExpr(const InitListExpr *E);
7764 bool VisitUnaryImag(const UnaryOperator *E);
7765 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
7766 // binary comparisons, binary and/or/xor,
7767 // shufflevector, ExtVectorElementExpr
7768 };
7769} // end anonymous namespace
7770
7771static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
7772 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
7773 return VectorExprEvaluator(Info, Result).Visit(E);
7774}
7775
7776bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
7777 const VectorType *VTy = E->getType()->castAs<VectorType>();
7778 unsigned NElts = VTy->getNumElements();
7779
7780 const Expr *SE = E->getSubExpr();
7781 QualType SETy = SE->getType();
7782
7783 switch (E->getCastKind()) {
7784 case CK_VectorSplat: {
7785 APValue Val = APValue();
7786 if (SETy->isIntegerType()) {
7787 APSInt IntResult;
7788 if (!EvaluateInteger(SE, IntResult, Info))
7789 return false;
7790 Val = APValue(std::move(IntResult));
7791 } else if (SETy->isRealFloatingType()) {
7792 APFloat FloatResult(0.0);
7793 if (!EvaluateFloat(SE, FloatResult, Info))
7794 return false;
7795 Val = APValue(std::move(FloatResult));
7796 } else {
7797 return Error(E);
7798 }
7799
7800 // Splat and create vector APValue.
7801 SmallVector<APValue, 4> Elts(NElts, Val);
7802 return Success(Elts, E);
7803 }
7804 case CK_BitCast: {
7805 // Evaluate the operand into an APInt we can extract from.
7806 llvm::APInt SValInt;
7807 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
7808 return false;
7809 // Extract the elements
7810 QualType EltTy = VTy->getElementType();
7811 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
7812 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7813 SmallVector<APValue, 4> Elts;
7814 if (EltTy->isRealFloatingType()) {
7815 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
7816 unsigned FloatEltSize = EltSize;
7817 if (&Sem == &APFloat::x87DoubleExtended())
7818 FloatEltSize = 80;
7819 for (unsigned i = 0; i < NElts; i++) {
7820 llvm::APInt Elt;
7821 if (BigEndian)
7822 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
7823 else
7824 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
7825 Elts.push_back(APValue(APFloat(Sem, Elt)));
7826 }
7827 } else if (EltTy->isIntegerType()) {
7828 for (unsigned i = 0; i < NElts; i++) {
7829 llvm::APInt Elt;
7830 if (BigEndian)
7831 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
7832 else
7833 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
7834 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
7835 }
7836 } else {
7837 return Error(E);
7838 }
7839 return Success(Elts, E);
7840 }
7841 default:
7842 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7843 }
7844}
7845
7846bool
7847VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7848 const VectorType *VT = E->getType()->castAs<VectorType>();
7849 unsigned NumInits = E->getNumInits();
7850 unsigned NumElements = VT->getNumElements();
7851
7852 QualType EltTy = VT->getElementType();
7853 SmallVector<APValue, 4> Elements;
7854
7855 // The number of initializers can be less than the number of
7856 // vector elements. For OpenCL, this can be due to nested vector
7857 // initialization. For GCC compatibility, missing trailing elements
7858 // should be initialized with zeroes.
7859 unsigned CountInits = 0, CountElts = 0;
7860 while (CountElts < NumElements) {
7861 // Handle nested vector initialization.
7862 if (CountInits < NumInits
7863 && E->getInit(CountInits)->getType()->isVectorType()) {
7864 APValue v;
7865 if (!EvaluateVector(E->getInit(CountInits), v, Info))
7866 return Error(E);
7867 unsigned vlen = v.getVectorLength();
7868 for (unsigned j = 0; j < vlen; j++)
7869 Elements.push_back(v.getVectorElt(j));
7870 CountElts += vlen;
7871 } else if (EltTy->isIntegerType()) {
7872 llvm::APSInt sInt(32);
7873 if (CountInits < NumInits) {
7874 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
7875 return false;
7876 } else // trailing integer zero.
7877 sInt = Info.Ctx.MakeIntValue(0, EltTy);
7878 Elements.push_back(APValue(sInt));
7879 CountElts++;
7880 } else {
7881 llvm::APFloat f(0.0);
7882 if (CountInits < NumInits) {
7883 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
7884 return false;
7885 } else // trailing float zero.
7886 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
7887 Elements.push_back(APValue(f));
7888 CountElts++;
7889 }
7890 CountInits++;
7891 }
7892 return Success(Elements, E);
7893}
7894
7895bool
7896VectorExprEvaluator::ZeroInitialization(const Expr *E) {
7897 const VectorType *VT = E->getType()->getAs<VectorType>();
7898 QualType EltTy = VT->getElementType();
7899 APValue ZeroElement;
7900 if (EltTy->isIntegerType())
7901 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
7902 else
7903 ZeroElement =
7904 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
7905
7906 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
7907 return Success(Elements, E);
7908}
7909
7910bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7911 VisitIgnoredValue(E->getSubExpr());
7912 return ZeroInitialization(E);
7913}
7914
7915//===----------------------------------------------------------------------===//
7916// Array Evaluation
7917//===----------------------------------------------------------------------===//
7918
7919namespace {
7920 class ArrayExprEvaluator
7921 : public ExprEvaluatorBase<ArrayExprEvaluator> {
7922 const LValue &This;
7923 APValue &Result;
7924 public:
7925
7926 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
7927 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
7928
7929 bool Success(const APValue &V, const Expr *E) {
7930 assert(V.isArray() && "expected array");
7931 Result = V;
7932 return true;
7933 }
7934
7935 bool ZeroInitialization(const Expr *E) {
7936 const ConstantArrayType *CAT =
7937 Info.Ctx.getAsConstantArrayType(E->getType());
7938 if (!CAT)
7939 return Error(E);
7940
7941 Result = APValue(APValue::UninitArray(), 0,
7942 CAT->getSize().getZExtValue());
7943 if (!Result.hasArrayFiller()) return true;
7944
7945 // Zero-initialize all elements.
7946 LValue Subobject = This;
7947 Subobject.addArray(Info, E, CAT);
7948 ImplicitValueInitExpr VIE(CAT->getElementType());
7949 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
7950 }
7951
7952 bool VisitCallExpr(const CallExpr *E) {
7953 return handleCallExpr(E, Result, &This);
7954 }
7955 bool VisitInitListExpr(const InitListExpr *E);
7956 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
7957 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
7958 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
7959 const LValue &Subobject,
7960 APValue *Value, QualType Type);
7961 bool VisitStringLiteral(const StringLiteral *E) {
7962 expandStringLiteral(Info, E, Result);
7963 return true;
7964 }
7965 };
7966} // end anonymous namespace
7967
7968static bool EvaluateArray(const Expr *E, const LValue &This,
7969 APValue &Result, EvalInfo &Info) {
7970 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
7971 return ArrayExprEvaluator(Info, This, Result).Visit(E);
7972}
7973
7974// Return true iff the given array filler may depend on the element index.
7975static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
7976 // For now, just whitelist non-class value-initialization and initialization
7977 // lists comprised of them.
7978 if (isa<ImplicitValueInitExpr>(FillerExpr))
7979 return false;
7980 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
7981 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
7982 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
7983 return true;
7984 }
7985 return false;
7986 }
7987 return true;
7988}
7989
7990bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7991 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
7992 if (!CAT)
7993 return Error(E);
7994
7995 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
7996 // an appropriately-typed string literal enclosed in braces.
7997 if (E->isStringLiteralInit())
7998 return Visit(E->getInit(0));
7999
8000 bool Success = true;
8001
8002 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
8003 "zero-initialized array shouldn't have any initialized elts");
8004 APValue Filler;
8005 if (Result.isArray() && Result.hasArrayFiller())
8006 Filler = Result.getArrayFiller();
8007
8008 unsigned NumEltsToInit = E->getNumInits();
8009 unsigned NumElts = CAT->getSize().getZExtValue();
8010 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
8011
8012 // If the initializer might depend on the array index, run it for each
8013 // array element.
8014 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
8015 NumEltsToInit = NumElts;
8016
8017 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
8018 << NumEltsToInit << ".\n");
8019
8020 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
8021
8022 // If the array was previously zero-initialized, preserve the
8023 // zero-initialized values.
8024 if (Filler.hasValue()) {
8025 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
8026 Result.getArrayInitializedElt(I) = Filler;
8027 if (Result.hasArrayFiller())
8028 Result.getArrayFiller() = Filler;
8029 }
8030
8031 LValue Subobject = This;
8032 Subobject.addArray(Info, E, CAT);
8033 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
8034 const Expr *Init =
8035 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
8036 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8037 Info, Subobject, Init) ||
8038 !HandleLValueArrayAdjustment(Info, Init, Subobject,
8039 CAT->getElementType(), 1)) {
8040 if (!Info.noteFailure())
8041 return false;
8042 Success = false;
8043 }
8044 }
8045
8046 if (!Result.hasArrayFiller())
8047 return Success;
8048
8049 // If we get here, we have a trivial filler, which we can just evaluate
8050 // once and splat over the rest of the array elements.
8051 assert(FillerExpr && "no array filler for incomplete init list");
8052 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
8053 FillerExpr) && Success;
8054}
8055
8056bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
8057 if (E->getCommonExpr() &&
8058 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
8059 Info, E->getCommonExpr()->getSourceExpr()))
8060 return false;
8061
8062 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
8063
8064 uint64_t Elements = CAT->getSize().getZExtValue();
8065 Result = APValue(APValue::UninitArray(), Elements, Elements);
8066
8067 LValue Subobject = This;
8068 Subobject.addArray(Info, E, CAT);
8069
8070 bool Success = true;
8071 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
8072 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8073 Info, Subobject, E->getSubExpr()) ||
8074 !HandleLValueArrayAdjustment(Info, E, Subobject,
8075 CAT->getElementType(), 1)) {
8076 if (!Info.noteFailure())
8077 return false;
8078 Success = false;
8079 }
8080 }
8081
8082 return Success;
8083}
8084
8085bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
8086 return VisitCXXConstructExpr(E, This, &Result, E->getType());
8087}
8088
8089bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8090 const LValue &Subobject,
8091 APValue *Value,
8092 QualType Type) {
8093 bool HadZeroInit = Value->hasValue();
8094
8095 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
8096 unsigned N = CAT->getSize().getZExtValue();
8097
8098 // Preserve the array filler if we had prior zero-initialization.
8099 APValue Filler =
8100 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
8101 : APValue();
8102
8103 *Value = APValue(APValue::UninitArray(), N, N);
8104
8105 if (HadZeroInit)
8106 for (unsigned I = 0; I != N; ++I)
8107 Value->getArrayInitializedElt(I) = Filler;
8108
8109 // Initialize the elements.
8110 LValue ArrayElt = Subobject;
8111 ArrayElt.addArray(Info, E, CAT);
8112 for (unsigned I = 0; I != N; ++I)
8113 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
8114 CAT->getElementType()) ||
8115 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
8116 CAT->getElementType(), 1))
8117 return false;
8118
8119 return true;
8120 }
8121
8122 if (!Type->isRecordType())
8123 return Error(E);
8124
8125 return RecordExprEvaluator(Info, Subobject, *Value)
8126 .VisitCXXConstructExpr(E, Type);
8127}
8128
8129//===----------------------------------------------------------------------===//
8130// Integer Evaluation
8131//
8132// As a GNU extension, we support casting pointers to sufficiently-wide integer
8133// types and back in constant folding. Integer values are thus represented
8134// either as an integer-valued APValue, or as an lvalue-valued APValue.
8135//===----------------------------------------------------------------------===//
8136
8137namespace {
8138class IntExprEvaluator
8139 : public ExprEvaluatorBase<IntExprEvaluator> {
8140 APValue &Result;
8141public:
8142 IntExprEvaluator(EvalInfo &info, APValue &result)
8143 : ExprEvaluatorBaseTy(info), Result(result) {}
8144
8145 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
8146 assert(E->getType()->isIntegralOrEnumerationType() &&
8147 "Invalid evaluation result.");
8148 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
8149 "Invalid evaluation result.");
8150 assert(SI.getBitWidth() == Info.Ctx.getIntRange(E->getType()) &&
8151 "Invalid evaluation result.");
8152 Result = APValue(SI);
8153 return true;
8154 }
8155 bool Success(const llvm::APSInt &SI, const Expr *E) {
8156 return Success(SI, E, Result);
8157 }
8158
8159 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
8160 assert(E->getType()->isIntegralOrEnumerationType() &&
8161 "Invalid evaluation result.");
8162 assert(I.getBitWidth() == Info.Ctx.getIntRange(E->getType()) &&
8163 "Invalid evaluation result.");
8164 Result = APValue(APSInt(I));
8165 Result.getInt().setIsUnsigned(
8166 E->getType()->isUnsignedIntegerOrEnumerationType());
8167 return true;
8168 }
8169 bool Success(const llvm::APInt &I, const Expr *E) {
8170 return Success(I, E, Result);
8171 }
8172
8173 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8174 assert(E->getType()->isIntegralOrEnumerationType() &&
8175 "Invalid evaluation result.");
8176 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
8177 return true;
8178 }
8179 bool Success(uint64_t Value, const Expr *E) {
8180 return Success(Value, E, Result);
8181 }
8182
8183 bool Success(CharUnits Size, const Expr *E) {
8184 return Success(Size.getQuantity(), E);
8185 }
8186
8187 bool Success(const APValue &V, const Expr *E) {
8188 if (V.isLValue() || V.isAddrLabelDiff()) {
8189 Result = V;
8190 return true;
8191 }
8192 return Success(V.getInt(), E);
8193 }
8194
8195 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
8196
8197 //===--------------------------------------------------------------------===//
8198 // Visitor Methods
8199 //===--------------------------------------------------------------------===//
8200
8201 bool VisitConstantExpr(const ConstantExpr *E);
8202
8203 bool VisitIntegerLiteral(const IntegerLiteral *E) {
8204 return Success(E->getValue(), E);
8205 }
8206 bool VisitCharacterLiteral(const CharacterLiteral *E) {
8207 return Success(E->getValue(), E);
8208 }
8209
8210 bool CheckReferencedDecl(const Expr *E, const Decl *D);
8211 bool VisitDeclRefExpr(const DeclRefExpr *E) {
8212 if (CheckReferencedDecl(E, E->getDecl()))
8213 return true;
8214
8215 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
8216 }
8217 bool VisitMemberExpr(const MemberExpr *E) {
8218 if (CheckReferencedDecl(E, E->getMemberDecl())) {
8219 VisitIgnoredBaseExpression(E->getBase());
8220 return true;
8221 }
8222
8223 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
8224 }
8225
8226 bool VisitCallExpr(const CallExpr *E);
8227 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8228 bool VisitBinaryOperator(const BinaryOperator *E);
8229 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
8230 bool VisitUnaryOperator(const UnaryOperator *E);
8231
8232 bool VisitCastExpr(const CastExpr* E);
8233 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
8234
8235 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
8236 return Success(E->getValue(), E);
8237 }
8238
8239 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
8240 return Success(E->getValue(), E);
8241 }
8242
8243 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
8244 if (Info.ArrayInitIndex == uint64_t(-1)) {
8245 // We were asked to evaluate this subexpression independent of the
8246 // enclosing ArrayInitLoopExpr. We can't do that.
8247 Info.FFDiag(E);
8248 return false;
8249 }
8250 return Success(Info.ArrayInitIndex, E);
8251 }
8252
8253 // Note, GNU defines __null as an integer, not a pointer.
8254 bool VisitGNUNullExpr(const GNUNullExpr *E) {
8255 return ZeroInitialization(E);
8256 }
8257
8258 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
8259 return Success(E->getValue(), E);
8260 }
8261
8262 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
8263 return Success(E->getValue(), E);
8264 }
8265
8266 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
8267 return Success(E->getValue(), E);
8268 }
8269
8270 bool VisitUnaryReal(const UnaryOperator *E);
8271 bool VisitUnaryImag(const UnaryOperator *E);
8272
8273 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
8274 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
8275 bool VisitSourceLocExpr(const SourceLocExpr *E);
8276 // FIXME: Missing: array subscript of vector, member of vector
8277};
8278
8279class FixedPointExprEvaluator
8280 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
8281 APValue &Result;
8282
8283 public:
8284 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
8285 : ExprEvaluatorBaseTy(info), Result(result) {}
8286
8287 bool Success(const llvm::APInt &I, const Expr *E) {
8288 return Success(
8289 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
8290 }
8291
8292 bool Success(uint64_t Value, const Expr *E) {
8293 return Success(
8294 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
8295 }
8296
8297 bool Success(const APValue &V, const Expr *E) {
8298 return Success(V.getFixedPoint(), E);
8299 }
8300
8301 bool Success(const APFixedPoint &V, const Expr *E) {
8302 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
8303 assert(V.getWidth() == Info.Ctx.getIntRange(E->getType()) &&
8304 "Invalid evaluation result.");
8305 Result = APValue(V);
8306 return true;
8307 }
8308
8309 //===--------------------------------------------------------------------===//
8310 // Visitor Methods
8311 //===--------------------------------------------------------------------===//
8312
8313 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
8314 return Success(E->getValue(), E);
8315 }
8316
8317 bool VisitCastExpr(const CastExpr *E);
8318 bool VisitUnaryOperator(const UnaryOperator *E);
8319 bool VisitBinaryOperator(const BinaryOperator *E);
8320};
8321} // end anonymous namespace
8322
8323/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
8324/// produce either the integer value or a pointer.
8325///
8326/// GCC has a heinous extension which folds casts between pointer types and
8327/// pointer-sized integral types. We support this by allowing the evaluation of
8328/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
8329/// Some simple arithmetic on such values is supported (they are treated much
8330/// like char*).
8331static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
8332 EvalInfo &Info) {
8333 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
8334 return IntExprEvaluator(Info, Result).Visit(E);
8335}
8336
8337static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
8338 APValue Val;
8339 if (!EvaluateIntegerOrLValue(E, Val, Info))
8340 return false;
8341 if (!Val.isInt()) {
8342 // FIXME: It would be better to produce the diagnostic for casting
8343 // a pointer to an integer.
8344 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8345 return false;
8346 }
8347 Result = Val.getInt();
8348 return true;
8349}
8350
8351bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
8352 APValue Evaluated = E->EvaluateInContext(
8353 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8354 return Success(Evaluated, E);
8355}
8356
8357static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
8358 EvalInfo &Info) {
8359 if (E->getType()->isFixedPointType()) {
8360 APValue Val;
8361 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
8362 return false;
8363 if (!Val.isFixedPoint())
8364 return false;
8365
8366 Result = Val.getFixedPoint();
8367 return true;
8368 }
8369 return false;
8370}
8371
8372static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
8373 EvalInfo &Info) {
8374 if (E->getType()->isIntegerType()) {
8375 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
8376 APSInt Val;
8377 if (!EvaluateInteger(E, Val, Info))
8378 return false;
8379 Result = APFixedPoint(Val, FXSema);
8380 return true;
8381 } else if (E->getType()->isFixedPointType()) {
8382 return EvaluateFixedPoint(E, Result, Info);
8383 }
8384 return false;
8385}
8386
8387/// Check whether the given declaration can be directly converted to an integral
8388/// rvalue. If not, no diagnostic is produced; there are other things we can
8389/// try.
8390bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
8391 // Enums are integer constant exprs.
8392 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
8393 // Check for signedness/width mismatches between E type and ECD value.
8394 bool SameSign = (ECD->getInitVal().isSigned()
8395 == E->getType()->isSignedIntegerOrEnumerationType());
8396 bool SameWidth = (ECD->getInitVal().getBitWidth()
8397 == Info.Ctx.getIntRange(E->getType()));
8398 if (SameSign && SameWidth)
8399 return Success(ECD->getInitVal(), E);
8400 else {
8401 // Get rid of mismatch (otherwise Success assertions will fail)
8402 // by computing a new value matching the type of E.
8403 llvm::APSInt Val = ECD->getInitVal();
8404 if (!SameSign)
8405 Val.setIsSigned(!ECD->getInitVal().isSigned());
8406 if (!SameWidth)
8407 Val = Val.extOrTrunc(Info.Ctx.getIntRange(E->getType()));
8408 return Success(Val, E);
8409 }
8410 }
8411 return false;
8412}
8413
8414/// Values returned by __builtin_classify_type, chosen to match the values
8415/// produced by GCC's builtin.
8416enum class GCCTypeClass {
8417 None = -1,
8418 Void = 0,
8419 Integer = 1,
8420 // GCC reserves 2 for character types, but instead classifies them as
8421 // integers.
8422 Enum = 3,
8423 Bool = 4,
8424 Pointer = 5,
8425 // GCC reserves 6 for references, but appears to never use it (because
8426 // expressions never have reference type, presumably).
8427 PointerToDataMember = 7,
8428 RealFloat = 8,
8429 Complex = 9,
8430 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
8431 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
8432 // GCC claims to reserve 11 for pointers to member functions, but *actually*
8433 // uses 12 for that purpose, same as for a class or struct. Maybe it
8434 // internally implements a pointer to member as a struct? Who knows.
8435 PointerToMemberFunction = 12, // Not a bug, see above.
8436 ClassOrStruct = 12,
8437 Union = 13,
8438 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
8439 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
8440 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
8441 // literals.
8442};
8443
8444/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8445/// as GCC.
8446static GCCTypeClass
8447EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
8448 assert(!T->isDependentType() && "unexpected dependent type");
8449
8450 QualType CanTy = T.getCanonicalType();
8451 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
8452
8453 switch (CanTy->getTypeClass()) {
8454#define TYPE(ID, BASE)
8455#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
8456#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
8457#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
8458#include "clang/AST/TypeNodes.def"
8459 case Type::Auto:
8460 case Type::DeducedTemplateSpecialization:
8461 llvm_unreachable("unexpected non-canonical or dependent type");
8462
8463 case Type::Builtin:
8464 switch (BT->getKind()) {
8465#define BUILTIN_TYPE(ID, SINGLETON_ID)
8466#define SIGNED_TYPE(ID, SINGLETON_ID) \
8467 case BuiltinType::ID: return GCCTypeClass::Integer;
8468#define FLOATING_TYPE(ID, SINGLETON_ID) \
8469 case BuiltinType::ID: return GCCTypeClass::RealFloat;
8470#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
8471 case BuiltinType::ID: break;
8472#include "clang/AST/BuiltinTypes.def"
8473 case BuiltinType::Void:
8474 return GCCTypeClass::Void;
8475
8476 case BuiltinType::Bool:
8477 return GCCTypeClass::Bool;
8478
8479 case BuiltinType::Char_U:
8480 case BuiltinType::UChar:
8481 case BuiltinType::WChar_U:
8482 case BuiltinType::Char8:
8483 case BuiltinType::Char16:
8484 case BuiltinType::Char32:
8485 case BuiltinType::UShort:
8486 case BuiltinType::UInt:
8487 case BuiltinType::ULong:
8488 case BuiltinType::ULongLong:
8489 case BuiltinType::UInt128:
8490 case BuiltinType::UIntCap:
8491 return GCCTypeClass::Integer;
8492
8493 case BuiltinType::UShortAccum:
8494 case BuiltinType::UAccum:
8495 case BuiltinType::ULongAccum:
8496 case BuiltinType::UShortFract:
8497 case BuiltinType::UFract:
8498 case BuiltinType::ULongFract:
8499 case BuiltinType::SatUShortAccum:
8500 case BuiltinType::SatUAccum:
8501 case BuiltinType::SatULongAccum:
8502 case BuiltinType::SatUShortFract:
8503 case BuiltinType::SatUFract:
8504 case BuiltinType::SatULongFract:
8505 return GCCTypeClass::None;
8506
8507 case BuiltinType::NullPtr:
8508
8509 case BuiltinType::ObjCId:
8510 case BuiltinType::ObjCClass:
8511 case BuiltinType::ObjCSel:
8512#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8513 case BuiltinType::Id:
8514#include "clang/Basic/OpenCLImageTypes.def"
8515#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8516 case BuiltinType::Id:
8517#include "clang/Basic/OpenCLExtensionTypes.def"
8518 case BuiltinType::OCLSampler:
8519 case BuiltinType::OCLEvent:
8520 case BuiltinType::OCLClkEvent:
8521 case BuiltinType::OCLQueue:
8522 case BuiltinType::OCLReserveID:
8523 return GCCTypeClass::None;
8524
8525 case BuiltinType::Dependent:
8526 llvm_unreachable("unexpected dependent type");
8527 };
8528 llvm_unreachable("unexpected placeholder type");
8529
8530 case Type::Enum:
8531 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
8532
8533 case Type::Pointer:
8534 case Type::ConstantArray:
8535 case Type::VariableArray:
8536 case Type::IncompleteArray:
8537 case Type::FunctionNoProto:
8538 case Type::FunctionProto:
8539 return GCCTypeClass::Pointer;
8540
8541 case Type::MemberPointer:
8542 return CanTy->isMemberDataPointerType()
8543 ? GCCTypeClass::PointerToDataMember
8544 : GCCTypeClass::PointerToMemberFunction;
8545
8546 case Type::Complex:
8547 return GCCTypeClass::Complex;
8548
8549 case Type::Record:
8550 return CanTy->isUnionType() ? GCCTypeClass::Union
8551 : GCCTypeClass::ClassOrStruct;
8552
8553 case Type::Atomic:
8554 // GCC classifies _Atomic T the same as T.
8555 return EvaluateBuiltinClassifyType(
8556 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
8557
8558 case Type::BlockPointer:
8559 case Type::Vector:
8560 case Type::ExtVector:
8561 case Type::ObjCObject:
8562 case Type::ObjCInterface:
8563 case Type::ObjCObjectPointer:
8564 case Type::Pipe:
8565 // GCC classifies vectors as None. We follow its lead and classify all
8566 // other types that don't fit into the regular classification the same way.
8567 return GCCTypeClass::None;
8568
8569 case Type::LValueReference:
8570 case Type::RValueReference:
8571 llvm_unreachable("invalid type for expression");
8572 }
8573
8574 llvm_unreachable("unexpected type class");
8575}
8576
8577/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8578/// as GCC.
8579static GCCTypeClass
8580EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
8581 // If no argument was supplied, default to None. This isn't
8582 // ideal, however it is what gcc does.
8583 if (E->getNumArgs() == 0)
8584 return GCCTypeClass::None;
8585
8586 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
8587 // being an ICE, but still folds it to a constant using the type of the first
8588 // argument.
8589 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
8590}
8591
8592/// EvaluateBuiltinConstantPForLValue - Determine the result of
8593/// __builtin_constant_p when applied to the given pointer.
8594///
8595/// A pointer is only "constant" if it is null (or a pointer cast to integer)
8596/// or it points to the first character of a string literal.
8597static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
8598 APValue::LValueBase Base = LV.getLValueBase();
8599 if (Base.isNull()) {
8600 // A null base is acceptable.
8601 return true;
8602 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
8603 if (!isa<StringLiteral>(E))
8604 return false;
8605 return LV.getLValueOffset().isZero();
8606 } else if (Base.is<TypeInfoLValue>()) {
8607 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
8608 // evaluate to true.
8609 return true;
8610 } else {
8611 // Any other base is not constant enough for GCC.
8612 return false;
8613 }
8614}
8615
8616/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
8617/// GCC as we can manage.
8618static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
8619 // This evaluation is not permitted to have side-effects, so evaluate it in
8620 // a speculative evaluation context.
8621 SpeculativeEvaluationRAII SpeculativeEval(Info);
8622
8623 // Constant-folding is always enabled for the operand of __builtin_constant_p
8624 // (even when the enclosing evaluation context otherwise requires a strict
8625 // language-specific constant expression).
8626 FoldConstant Fold(Info, true);
8627
8628 QualType ArgType = Arg->getType();
8629
8630 // __builtin_constant_p always has one operand. The rules which gcc follows
8631 // are not precisely documented, but are as follows:
8632 //
8633 // - If the operand is of integral, floating, complex or enumeration type,
8634 // and can be folded to a known value of that type, it returns 1.
8635 // - If the operand can be folded to a pointer to the first character
8636 // of a string literal (or such a pointer cast to an integral type)
8637 // or to a null pointer or an integer cast to a pointer, it returns 1.
8638 //
8639 // Otherwise, it returns 0.
8640 //
8641 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
8642 // its support for this did not work prior to GCC 9 and is not yet well
8643 // understood.
8644 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
8645 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
8646 ArgType->isNullPtrType()) {
8647 APValue V;
8648 if (!::EvaluateAsRValue(Info, Arg, V)) {
8649 Fold.keepDiagnostics();
8650 return false;
8651 }
8652
8653 // For a pointer (possibly cast to integer), there are special rules.
8654 if (V.getKind() == APValue::LValue)
8655 return EvaluateBuiltinConstantPForLValue(V);
8656
8657 // Otherwise, any constant value is good enough.
8658 return V.hasValue();
8659 }
8660
8661 // Anything else isn't considered to be sufficiently constant.
8662 return false;
8663}
8664
8665/// Retrieves the "underlying object type" of the given expression,
8666/// as used by __builtin_object_size.
8667static QualType getObjectType(APValue::LValueBase B) {
8668 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
8669 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8670 return VD->getType();
8671 } else if (const Expr *E = B.get<const Expr*>()) {
8672 if (isa<CompoundLiteralExpr>(E))
8673 return E->getType();
8674 } else if (B.is<TypeInfoLValue>()) {
8675 return B.getTypeInfoType();
8676 }
8677
8678 return QualType();
8679}
8680
8681/// A more selective version of E->IgnoreParenCasts for
8682/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
8683/// to change the type of E.
8684/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
8685///
8686/// Always returns an RValue with a pointer representation.
8687static const Expr *ignorePointerCastsAndParens(const Expr *E) {
8688 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8689
8690 auto *NoParens = E->IgnoreParens();
8691 auto *Cast = dyn_cast<CastExpr>(NoParens);
8692 if (Cast == nullptr)
8693 return NoParens;
8694
8695 // We only conservatively allow a few kinds of casts, because this code is
8696 // inherently a simple solution that seeks to support the common case.
8697 auto CastKind = Cast->getCastKind();
8698 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
8699 CastKind != CK_AddressSpaceConversion)
8700 return NoParens;
8701
8702 auto *SubExpr = Cast->getSubExpr();
8703 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
8704 return NoParens;
8705 return ignorePointerCastsAndParens(SubExpr);
8706}
8707
8708/// Checks to see if the given LValue's Designator is at the end of the LValue's
8709/// record layout. e.g.
8710/// struct { struct { int a, b; } fst, snd; } obj;
8711/// obj.fst // no
8712/// obj.snd // yes
8713/// obj.fst.a // no
8714/// obj.fst.b // no
8715/// obj.snd.a // no
8716/// obj.snd.b // yes
8717///
8718/// Please note: this function is specialized for how __builtin_object_size
8719/// views "objects".
8720///
8721/// If this encounters an invalid RecordDecl or otherwise cannot determine the
8722/// correct result, it will always return true.
8723static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
8724 assert(!LVal.Designator.Invalid);
8725
8726 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
8727 const RecordDecl *Parent = FD->getParent();
8728 Invalid = Parent->isInvalidDecl();
8729 if (Invalid || Parent->isUnion())
8730 return true;
8731 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
8732 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
8733 };
8734
8735 auto &Base = LVal.getLValueBase();
8736 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
8737 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
8738 bool Invalid;
8739 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
8740 return Invalid;
8741 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
8742 for (auto *FD : IFD->chain()) {
8743 bool Invalid;
8744 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
8745 return Invalid;
8746 }
8747 }
8748 }
8749
8750 unsigned I = 0;
8751 QualType BaseType = getType(Base);
8752 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
8753 // If we don't know the array bound, conservatively assume we're looking at
8754 // the final array element.
8755 ++I;
8756 if (BaseType->isIncompleteArrayType())
8757 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
8758 else
8759 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
8760 }
8761
8762 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
8763 const auto &Entry = LVal.Designator.Entries[I];
8764 if (BaseType->isArrayType()) {
8765 // Because __builtin_object_size treats arrays as objects, we can ignore
8766 // the index iff this is the last array in the Designator.
8767 if (I + 1 == E)
8768 return true;
8769 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
8770 uint64_t Index = Entry.getAsArrayIndex();
8771 if (Index + 1 != CAT->getSize())
8772 return false;
8773 BaseType = CAT->getElementType();
8774 } else if (BaseType->isAnyComplexType()) {
8775 const auto *CT = BaseType->castAs<ComplexType>();
8776 uint64_t Index = Entry.getAsArrayIndex();
8777 if (Index != 1)
8778 return false;
8779 BaseType = CT->getElementType();
8780 } else if (auto *FD = getAsField(Entry)) {
8781 bool Invalid;
8782 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
8783 return Invalid;
8784 BaseType = FD->getType();
8785 } else {
8786 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
8787 return false;
8788 }
8789 }
8790 return true;
8791}
8792
8793/// Tests to see if the LValue has a user-specified designator (that isn't
8794/// necessarily valid). Note that this always returns 'true' if the LValue has
8795/// an unsized array as its first designator entry, because there's currently no
8796/// way to tell if the user typed *foo or foo[0].
8797static bool refersToCompleteObject(const LValue &LVal) {
8798 if (LVal.Designator.Invalid)
8799 return false;
8800
8801 if (!LVal.Designator.Entries.empty())
8802 return LVal.Designator.isMostDerivedAnUnsizedArray();
8803
8804 if (!LVal.InvalidBase)
8805 return true;
8806
8807 // If `E` is a MemberExpr, then the first part of the designator is hiding in
8808 // the LValueBase.
8809 const auto *E = LVal.Base.dyn_cast<const Expr *>();
8810 return !E || !isa<MemberExpr>(E);
8811}
8812
8813/// Attempts to detect a user writing into a piece of memory that's impossible
8814/// to figure out the size of by just using types.
8815static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
8816 const SubobjectDesignator &Designator = LVal.Designator;
8817 // Notes:
8818 // - Users can only write off of the end when we have an invalid base. Invalid
8819 // bases imply we don't know where the memory came from.
8820 // - We used to be a bit more aggressive here; we'd only be conservative if
8821 // the array at the end was flexible, or if it had 0 or 1 elements. This
8822 // broke some common standard library extensions (PR30346), but was
8823 // otherwise seemingly fine. It may be useful to reintroduce this behavior
8824 // with some sort of whitelist. OTOH, it seems that GCC is always
8825 // conservative with the last element in structs (if it's an array), so our
8826 // current behavior is more compatible than a whitelisting approach would
8827 // be.
8828 return LVal.InvalidBase &&
8829 Designator.Entries.size() == Designator.MostDerivedPathLength &&
8830 Designator.MostDerivedIsArrayElement &&
8831 isDesignatorAtObjectEnd(Ctx, LVal);
8832}
8833
8834/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
8835/// Fails if the conversion would cause loss of precision.
8836static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
8837 CharUnits &Result) {
8838 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
8839 if (Int.ugt(CharUnitsMax))
8840 return false;
8841 Result = CharUnits::fromQuantity(Int.getZExtValue());
8842 return true;
8843}
8844
8845/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
8846/// determine how many bytes exist from the beginning of the object to either
8847/// the end of the current subobject, or the end of the object itself, depending
8848/// on what the LValue looks like + the value of Type.
8849///
8850/// If this returns false, the value of Result is undefined.
8851static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
8852 unsigned Type, const LValue &LVal,
8853 CharUnits &EndOffset) {
8854 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
8855
8856 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
8857 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
8858 return false;
8859 return HandleSizeof(Info, ExprLoc, Ty, Result);
8860 };
8861
8862 // We want to evaluate the size of the entire object. This is a valid fallback
8863 // for when Type=1 and the designator is invalid, because we're asked for an
8864 // upper-bound.
8865 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
8866 // Type=3 wants a lower bound, so we can't fall back to this.
8867 if (Type == 3 && !DetermineForCompleteObject)
8868 return false;
8869
8870 llvm::APInt APEndOffset;
8871 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8872 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8873 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8874
8875 if (LVal.InvalidBase)
8876 return false;
8877
8878 QualType BaseTy = getObjectType(LVal.getLValueBase());
8879 return CheckedHandleSizeof(BaseTy, EndOffset);
8880 }
8881
8882 // We want to evaluate the size of a subobject.
8883 const SubobjectDesignator &Designator = LVal.Designator;
8884
8885 // The following is a moderately common idiom in C:
8886 //
8887 // struct Foo { int a; char c[1]; };
8888 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
8889 // strcpy(&F->c[0], Bar);
8890 //
8891 // In order to not break too much legacy code, we need to support it.
8892 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
8893 // If we can resolve this to an alloc_size call, we can hand that back,
8894 // because we know for certain how many bytes there are to write to.
8895 llvm::APInt APEndOffset;
8896 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8897 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8898 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8899
8900 // If we cannot determine the size of the initial allocation, then we can't
8901 // given an accurate upper-bound. However, we are still able to give
8902 // conservative lower-bounds for Type=3.
8903 if (Type == 1)
8904 return false;
8905 }
8906
8907 CharUnits BytesPerElem;
8908 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
8909 return false;
8910
8911 // According to the GCC documentation, we want the size of the subobject
8912 // denoted by the pointer. But that's not quite right -- what we actually
8913 // want is the size of the immediately-enclosing array, if there is one.
8914 int64_t ElemsRemaining;
8915 if (Designator.MostDerivedIsArrayElement &&
8916 Designator.Entries.size() == Designator.MostDerivedPathLength) {
8917 uint64_t ArraySize = Designator.getMostDerivedArraySize();
8918 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
8919 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
8920 } else {
8921 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
8922 }
8923
8924 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
8925 return true;
8926}
8927
8928/// Tries to evaluate the __builtin_object_size for @p E. If successful,
8929/// returns true and stores the result in @p Size.
8930///
8931/// If @p WasError is non-null, this will report whether the failure to evaluate
8932/// is to be treated as an Error in IntExprEvaluator.
8933static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
8934 EvalInfo &Info, uint64_t &Size) {
8935 // Determine the denoted object.
8936 LValue LVal;
8937 {
8938 // The operand of __builtin_object_size is never evaluated for side-effects.
8939 // If there are any, but we can determine the pointed-to object anyway, then
8940 // ignore the side-effects.
8941 SpeculativeEvaluationRAII SpeculativeEval(Info);
8942 IgnoreSideEffectsRAII Fold(Info);
8943
8944 if (E->isGLValue()) {
8945 // It's possible for us to be given GLValues if we're called via
8946 // Expr::tryEvaluateObjectSize.
8947 APValue RVal;
8948 if (!EvaluateAsRValue(Info, E, RVal))
8949 return false;
8950 LVal.setFrom(Info.Ctx, RVal);
8951 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
8952 /*InvalidBaseOK=*/true))
8953 return false;
8954 }
8955
8956 // If we point to before the start of the object, there are no accessible
8957 // bytes.
8958 if (LVal.getLValueOffset().isNegative()) {
8959 Size = 0;
8960 return true;
8961 }
8962
8963 CharUnits EndOffset;
8964 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
8965 return false;
8966
8967 // If we've fallen outside of the end offset, just pretend there's nothing to
8968 // write to/read from.
8969 if (EndOffset <= LVal.getLValueOffset())
8970 Size = 0;
8971 else
8972 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
8973 return true;
8974}
8975
8976bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
8977 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
8978 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
8979}
8980
8981bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
8982 if (unsigned BuiltinOp = E->getBuiltinCallee())
8983 return VisitBuiltinCallExpr(E, BuiltinOp);
8984
8985 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8986}
8987
8988static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
8989 bool IsPowerOfTwo, APSInt &Val,
8990 APSInt &Alignment, unsigned *ValWidth) {
8991 Expr::EvalResult ExprResult;
8992 if (!E->getArg(0)->EvaluateAsInt(ExprResult, Info.Ctx))
8993 return false;
8994 Val = ExprResult.Val.getInt();
8995 if (!E->getArg(1)->EvaluateAsInt(ExprResult, Info.Ctx))
8996 return false;
8997 Alignment = ExprResult.Val.getInt();
8998 if (Alignment < 0)
8999 return false;
9000 if (IsPowerOfTwo) {
9001 if (Alignment > 63)
9002 return false; // can't evaluate this
9003 unsigned SetBit = Alignment.getZExtValue();
9004 Alignment = APSInt(llvm::APInt::getOneBitSet(SetBit + 1, SetBit));
9005 }
9006 // XXXAR: can this ever happen? Will end up here even if Sema causes an error?
9007 // I guess this additional check doesn't do any harm
9008 if (!Alignment.isPowerOf2())
9009 return false;
9010 // ensure both values have the same bit width so that we don't assert later
9011 *ValWidth = Val.getBitWidth();
9012 if (Val.isUnsigned())
9013 Val = Val.zextOrSelf(Alignment.getBitWidth());
9014 else
9015 Val = Val.sextOrSelf(Alignment.getBitWidth());
9016 Alignment = Alignment.zextOrSelf(Val.getBitWidth());
9017 return true;
9018}
9019
9020bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9021 unsigned BuiltinOp) {
9022 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
9023 default:
9024 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9025
9026 case Builtin::BI__builtin_dynamic_object_size:
9027 case Builtin::BI__builtin_object_size: {
9028 // The type was checked when we built the expression.
9029 unsigned Type =
9030 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9031 assert(Type <= 3 && "unexpected type");
9032
9033 uint64_t Size;
9034 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
9035 return Success(Size, E);
9036
9037 if (E->getArg(0)->HasSideEffects(Info.Ctx))
9038 return Success((Type & 2) ? 0 : -1, E);
9039
9040 // Expression had no side effects, but we couldn't statically determine the
9041 // size of the referenced object.
9042 switch (Info.EvalMode) {
9043 case EvalInfo::EM_ConstantExpression:
9044 case EvalInfo::EM_PotentialConstantExpression:
9045 case EvalInfo::EM_ConstantFold:
9046 case EvalInfo::EM_EvaluateForOverflow:
9047 case EvalInfo::EM_IgnoreSideEffects:
9048 // Leave it to IR generation.
9049 return Error(E);
9050 case EvalInfo::EM_ConstantExpressionUnevaluated:
9051 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
9052 // Reduce it to a constant now.
9053 return Success((Type & 2) ? 0 : -1, E);
9054 }
9055
9056 llvm_unreachable("unexpected EvalMode");
9057 }
9058
9059 case Builtin::BI__builtin_os_log_format_buffer_size: {
9060 analyze_os_log::OSLogBufferLayout Layout;
9061 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
9062 return Success(Layout.size().getQuantity(), E);
9063 }
9064
9065 case Builtin::BI__builtin_is_aligned:
9066 case Builtin::BI__builtin_is_p2aligned: {
9067 APSInt Val;
9068 APSInt Alignment;
9069 unsigned ValWidth = -1;
9070 bool Pow2 = BuiltinOp == Builtin::BI__builtin_is_p2aligned;
9071 if (!getBuiltinAlignArguments(E, Info, Pow2, Val, Alignment, &ValWidth))
9072 return false;
9073 return Success((Val & (Alignment - 1)) == 0 ? 1 : 0, E);
9074 }
9075 case Builtin::BI__builtin_align_up:
9076 case Builtin::BI__builtin_p2align_up: {
9077 APSInt Val;
9078 APSInt Alignment;
9079 unsigned ValWidth = -1;
9080 bool Pow2 = BuiltinOp == Builtin::BI__builtin_p2align_up;
9081 if (!getBuiltinAlignArguments(E, Info, Pow2, Val, Alignment, &ValWidth))
9082 return false;
9083 // #define roundup2(x, y) (((x)+((y)-1))&(~((y)-1)))
9084 APSInt Result = APSInt((Val + (Alignment - 1)) & ~(Alignment - 1), Val.isUnsigned());
9085 return Success(Result.extOrTrunc(ValWidth), E);
9086 }
9087 case Builtin::BI__builtin_align_down:
9088 case Builtin::BI__builtin_p2align_down: {
9089 APSInt Val;
9090 APSInt Alignment;
9091 unsigned ValWidth = -1;
9092 bool Pow2 = BuiltinOp == Builtin::BI__builtin_p2align_down;
9093 if (!getBuiltinAlignArguments(E, Info, Pow2, Val, Alignment, &ValWidth))
9094 return false;
9095 // #define rounddown2(x, y) ((x)&(~((y)-1)))
9096 APSInt Result = APSInt(Val & ~(Alignment - 1), Val.isUnsigned());
9097 return Success(Result.extOrTrunc(ValWidth), E);
9098 }
9099
9100 case Builtin::BI__builtin_bswap16:
9101 case Builtin::BI__builtin_bswap32:
9102 case Builtin::BI__builtin_bswap64: {
9103 APSInt Val;
9104 if (!EvaluateInteger(E->getArg(0), Val, Info))
9105 return false;
9106
9107 return Success(Val.byteSwap(), E);
9108 }
9109
9110 case Builtin::BI__builtin_classify_type:
9111 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
9112
9113 case Builtin::BI__builtin_clrsb:
9114 case Builtin::BI__builtin_clrsbl:
9115 case Builtin::BI__builtin_clrsbll: {
9116 APSInt Val;
9117 if (!EvaluateInteger(E->getArg(0), Val, Info))
9118 return false;
9119
9120 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
9121 }
9122
9123 case Builtin::BI__builtin_clz:
9124 case Builtin::BI__builtin_clzl:
9125 case Builtin::BI__builtin_clzll:
9126 case Builtin::BI__builtin_clzs: {
9127 APSInt Val;
9128 if (!EvaluateInteger(E->getArg(0), Val, Info))
9129 return false;
9130 if (!Val)
9131 return Error(E);
9132
9133 return Success(Val.countLeadingZeros(), E);
9134 }
9135
9136 case Builtin::BI__builtin_constant_p: {
9137 const Expr *Arg = E->getArg(0);
9138 if (EvaluateBuiltinConstantP(Info, Arg))
9139 return Success(true, E);
9140 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
9141 // Outside a constant context, eagerly evaluate to false in the presence
9142 // of side-effects in order to avoid -Wunsequenced false-positives in
9143 // a branch on __builtin_constant_p(expr).
9144 return Success(false, E);
9145 }
9146 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9147 return false;
9148 }
9149
9150 case Builtin::BI__builtin_is_constant_evaluated:
9151 return Success(Info.InConstantContext, E);
9152
9153 case Builtin::BI__builtin_ctz:
9154 case Builtin::BI__builtin_ctzl:
9155 case Builtin::BI__builtin_ctzll:
9156 case Builtin::BI__builtin_ctzs: {
9157 APSInt Val;
9158 if (!EvaluateInteger(E->getArg(0), Val, Info))
9159 return false;
9160 if (!Val)
9161 return Error(E);
9162
9163 return Success(Val.countTrailingZeros(), E);
9164 }
9165
9166 case Builtin::BI__builtin_eh_return_data_regno: {
9167 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9168 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
9169 return Success(Operand, E);
9170 }
9171
9172 case Builtin::BI__builtin_expect:
9173 return Visit(E->getArg(0));
9174
9175 case Builtin::BI__builtin_ffs:
9176 case Builtin::BI__builtin_ffsl:
9177 case Builtin::BI__builtin_ffsll: {
9178 APSInt Val;
9179 if (!EvaluateInteger(E->getArg(0), Val, Info))
9180 return false;
9181
9182 unsigned N = Val.countTrailingZeros();
9183 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
9184 }
9185
9186 case Builtin::BI__builtin_fpclassify: {
9187 APFloat Val(0.0);
9188 if (!EvaluateFloat(E->getArg(5), Val, Info))
9189 return false;
9190 unsigned Arg;
9191 switch (Val.getCategory()) {
9192 case APFloat::fcNaN: Arg = 0; break;
9193 case APFloat::fcInfinity: Arg = 1; break;
9194 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
9195 case APFloat::fcZero: Arg = 4; break;
9196 }
9197 return Visit(E->getArg(Arg));
9198 }
9199
9200 case Builtin::BI__builtin_isinf_sign: {
9201 APFloat Val(0.0);
9202 return EvaluateFloat(E->getArg(0), Val, Info) &&
9203 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
9204 }
9205
9206 case Builtin::BI__builtin_isinf: {
9207 APFloat Val(0.0);
9208 return EvaluateFloat(E->getArg(0), Val, Info) &&
9209 Success(Val.isInfinity() ? 1 : 0, E);
9210 }
9211
9212 case Builtin::BI__builtin_isfinite: {
9213 APFloat Val(0.0);
9214 return EvaluateFloat(E->getArg(0), Val, Info) &&
9215 Success(Val.isFinite() ? 1 : 0, E);
9216 }
9217
9218 case Builtin::BI__builtin_isnan: {
9219 APFloat Val(0.0);
9220 return EvaluateFloat(E->getArg(0), Val, Info) &&
9221 Success(Val.isNaN() ? 1 : 0, E);
9222 }
9223
9224 case Builtin::BI__builtin_isnormal: {
9225 APFloat Val(0.0);
9226 return EvaluateFloat(E->getArg(0), Val, Info) &&
9227 Success(Val.isNormal() ? 1 : 0, E);
9228 }
9229
9230 case Builtin::BI__builtin_parity:
9231 case Builtin::BI__builtin_parityl:
9232 case Builtin::BI__builtin_parityll: {
9233 APSInt Val;
9234 if (!EvaluateInteger(E->getArg(0), Val, Info))
9235 return false;
9236
9237 return Success(Val.countPopulation() % 2, E);
9238 }
9239
9240 case Builtin::BI__builtin_popcount:
9241 case Builtin::BI__builtin_popcountl:
9242 case Builtin::BI__builtin_popcountll: {
9243 APSInt Val;
9244 if (!EvaluateInteger(E->getArg(0), Val, Info))
9245 return false;
9246
9247 return Success(Val.countPopulation(), E);
9248 }
9249
9250 case Builtin::BIstrlen:
9251 case Builtin::BIwcslen:
9252 // A call to strlen is not a constant expression.
9253 if (Info.getLangOpts().CPlusPlus11)
9254 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9255 << /*isConstexpr*/0 << /*isConstructor*/0
9256 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9257 else
9258 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9259 LLVM_FALLTHROUGH;
9260 case Builtin::BI__builtin_strlen:
9261 case Builtin::BI__builtin_wcslen: {
9262 // As an extension, we support __builtin_strlen() as a constant expression,
9263 // and support folding strlen() to a constant.
9264 LValue String;
9265 if (!EvaluatePointer(E->getArg(0), String, Info))
9266 return false;
9267
9268 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
9269
9270 // Fast path: if it's a string literal, search the string value.
9271 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
9272 String.getLValueBase().dyn_cast<const Expr *>())) {
9273 // The string literal may have embedded null characters. Find the first
9274 // one and truncate there.
9275 StringRef Str = S->getBytes();
9276 int64_t Off = String.Offset.getQuantity();
9277 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
9278 S->getCharByteWidth() == 1 &&
9279 // FIXME: Add fast-path for wchar_t too.
9280 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
9281 Str = Str.substr(Off);
9282
9283 StringRef::size_type Pos = Str.find(0);
9284 if (Pos != StringRef::npos)
9285 Str = Str.substr(0, Pos);
9286
9287 return Success(Str.size(), E);
9288 }
9289
9290 // Fall through to slow path to issue appropriate diagnostic.
9291 }
9292
9293 // Slow path: scan the bytes of the string looking for the terminating 0.
9294 for (uint64_t Strlen = 0; /**/; ++Strlen) {
9295 APValue Char;
9296 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
9297 !Char.isInt())
9298 return false;
9299 if (!Char.getInt())
9300 return Success(Strlen, E);
9301 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
9302 return false;
9303 }
9304 }
9305
9306 case Builtin::BIstrcmp:
9307 case Builtin::BIwcscmp:
9308 case Builtin::BIstrncmp:
9309 case Builtin::BIwcsncmp:
9310 case Builtin::BImemcmp:
9311 case Builtin::BIbcmp:
9312 case Builtin::BIwmemcmp:
9313 // A call to strlen is not a constant expression.
9314 if (Info.getLangOpts().CPlusPlus11)
9315 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9316 << /*isConstexpr*/0 << /*isConstructor*/0
9317 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9318 else
9319 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9320 LLVM_FALLTHROUGH;
9321 case Builtin::BI__builtin_strcmp:
9322 case Builtin::BI__builtin_wcscmp:
9323 case Builtin::BI__builtin_strncmp:
9324 case Builtin::BI__builtin_wcsncmp:
9325 case Builtin::BI__builtin_memcmp:
9326 case Builtin::BI__builtin_bcmp:
9327 case Builtin::BI__builtin_wmemcmp: {
9328 LValue String1, String2;
9329 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
9330 !EvaluatePointer(E->getArg(1), String2, Info))
9331 return false;
9332
9333 uint64_t MaxLength = uint64_t(-1);
9334 if (BuiltinOp != Builtin::BIstrcmp &&
9335 BuiltinOp != Builtin::BIwcscmp &&
9336 BuiltinOp != Builtin::BI__builtin_strcmp &&
9337 BuiltinOp != Builtin::BI__builtin_wcscmp) {
9338 APSInt N;
9339 if (!EvaluateInteger(E->getArg(2), N, Info))
9340 return false;
9341 MaxLength = N.getExtValue();
9342 }
9343
9344 // Empty substrings compare equal by definition.
9345 if (MaxLength == 0u)
9346 return Success(0, E);
9347
9348 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9349 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9350 String1.Designator.Invalid || String2.Designator.Invalid)
9351 return false;
9352
9353 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
9354 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
9355
9356 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
9357 BuiltinOp == Builtin::BIbcmp ||
9358 BuiltinOp == Builtin::BI__builtin_memcmp ||
9359 BuiltinOp == Builtin::BI__builtin_bcmp;
9360
9361 assert(IsRawByte ||
9362 (Info.Ctx.hasSameUnqualifiedType(
9363 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
9364 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
9365
9366 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
9367 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
9368 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
9369 Char1.isInt() && Char2.isInt();
9370 };
9371 const auto &AdvanceElems = [&] {
9372 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
9373 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
9374 };
9375
9376 if (IsRawByte) {
9377 uint64_t BytesRemaining = MaxLength;
9378 // Pointers to const void may point to objects of incomplete type.
9379 if (CharTy1->isIncompleteType()) {
9380 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
9381 return false;
9382 }
9383 if (CharTy2->isIncompleteType()) {
9384 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
9385 return false;
9386 }
9387 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
9388 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
9389 // Give up on comparing between elements with disparate widths.
9390 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
9391 return false;
9392 uint64_t BytesPerElement = CharTy1Size.getQuantity();
9393 assert(BytesRemaining && "BytesRemaining should not be zero: the "
9394 "following loop considers at least one element");
9395 while (true) {
9396 APValue Char1, Char2;
9397 if (!ReadCurElems(Char1, Char2))
9398 return false;
9399 // We have compatible in-memory widths, but a possible type and
9400 // (for `bool`) internal representation mismatch.
9401 // Assuming two's complement representation, including 0 for `false` and
9402 // 1 for `true`, we can check an appropriate number of elements for
9403 // equality even if they are not byte-sized.
9404 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
9405 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
9406 if (Char1InMem.ne(Char2InMem)) {
9407 // If the elements are byte-sized, then we can produce a three-way
9408 // comparison result in a straightforward manner.
9409 if (BytesPerElement == 1u) {
9410 // memcmp always compares unsigned chars.
9411 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
9412 }
9413 // The result is byte-order sensitive, and we have multibyte elements.
9414 // FIXME: We can compare the remaining bytes in the correct order.
9415 return false;
9416 }
9417 if (!AdvanceElems())
9418 return false;
9419 if (BytesRemaining <= BytesPerElement)
9420 break;
9421 BytesRemaining -= BytesPerElement;
9422 }
9423 // Enough elements are equal to account for the memcmp limit.
9424 return Success(0, E);
9425 }
9426
9427 bool StopAtNull =
9428 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
9429 BuiltinOp != Builtin::BIwmemcmp &&
9430 BuiltinOp != Builtin::BI__builtin_memcmp &&
9431 BuiltinOp != Builtin::BI__builtin_bcmp &&
9432 BuiltinOp != Builtin::BI__builtin_wmemcmp);
9433 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
9434 BuiltinOp == Builtin::BIwcsncmp ||
9435 BuiltinOp == Builtin::BIwmemcmp ||
9436 BuiltinOp == Builtin::BI__builtin_wcscmp ||
9437 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
9438 BuiltinOp == Builtin::BI__builtin_wmemcmp;
9439
9440 for (; MaxLength; --MaxLength) {
9441 APValue Char1, Char2;
9442 if (!ReadCurElems(Char1, Char2))
9443 return false;
9444 if (Char1.getInt() != Char2.getInt()) {
9445 if (IsWide) // wmemcmp compares with wchar_t signedness.
9446 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
9447 // memcmp always compares unsigned chars.
9448 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
9449 }
9450 if (StopAtNull && !Char1.getInt())
9451 return Success(0, E);
9452 assert(!(StopAtNull && !Char2.getInt()));
9453 if (!AdvanceElems())
9454 return false;
9455 }
9456 // We hit the strncmp / memcmp limit.
9457 return Success(0, E);
9458 }
9459
9460 case Builtin::BI__atomic_always_lock_free:
9461 case Builtin::BI__atomic_is_lock_free:
9462 case Builtin::BI__c11_atomic_is_lock_free: {
9463 APSInt SizeVal;
9464 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
9465 return false;
9466
9467 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
9468 // of two less than the maximum inline atomic width, we know it is
9469 // lock-free. If the size isn't a power of two, or greater than the
9470 // maximum alignment where we promote atomics, we know it is not lock-free
9471 // (at least not in the sense of atomic_is_lock_free). Otherwise,
9472 // the answer can only be determined at runtime; for example, 16-byte
9473 // atomics have lock-free implementations on some, but not all,
9474 // x86-64 processors.
9475
9476 // Check power-of-two.
9477 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
9478 if (Size.isPowerOfTwo()) {
9479 // Check against inlining width.
9480 unsigned InlineWidthBits =
9481 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
9482 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
9483 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
9484 Size == CharUnits::One() ||
9485 E->getArg(1)->isNullPointerConstant(Info.Ctx,
9486 Expr::NPC_NeverValueDependent))
9487 // OK, we will inline appropriately-aligned operations of this size,
9488 // and _Atomic(T) is appropriately-aligned.
9489 return Success(1, E);
9490
9491 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
9492 castAs<PointerType>()->getPointeeType();
9493 if (!PointeeType->isIncompleteType() &&
9494 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
9495 // OK, we will inline operations on this object.
9496 return Success(1, E);
9497 }
9498 }
9499 }
9500
9501 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
9502 Success(0, E) : Error(E);
9503 }
9504 case Builtin::BIomp_is_initial_device:
9505 // We can decide statically which value the runtime would return if called.
9506 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
9507 case Builtin::BI__builtin_add_overflow:
9508 case Builtin::BI__builtin_sub_overflow:
9509 case Builtin::BI__builtin_mul_overflow:
9510 case Builtin::BI__builtin_sadd_overflow:
9511 case Builtin::BI__builtin_uadd_overflow:
9512 case Builtin::BI__builtin_uaddl_overflow:
9513 case Builtin::BI__builtin_uaddll_overflow:
9514 case Builtin::BI__builtin_usub_overflow:
9515 case Builtin::BI__builtin_usubl_overflow:
9516 case Builtin::BI__builtin_usubll_overflow:
9517 case Builtin::BI__builtin_umul_overflow:
9518 case Builtin::BI__builtin_umull_overflow:
9519 case Builtin::BI__builtin_umulll_overflow:
9520 case Builtin::BI__builtin_saddl_overflow:
9521 case Builtin::BI__builtin_saddll_overflow:
9522 case Builtin::BI__builtin_ssub_overflow:
9523 case Builtin::BI__builtin_ssubl_overflow:
9524 case Builtin::BI__builtin_ssubll_overflow:
9525 case Builtin::BI__builtin_smul_overflow:
9526 case Builtin::BI__builtin_smull_overflow:
9527 case Builtin::BI__builtin_smulll_overflow: {
9528 LValue ResultLValue;
9529 APSInt LHS, RHS;
9530
9531 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
9532 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
9533 !EvaluateInteger(E->getArg(1), RHS, Info) ||
9534 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
9535 return false;
9536
9537 APSInt Result;
9538 bool DidOverflow = false;
9539
9540 // If the types don't have to match, enlarge all 3 to the largest of them.
9541 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9542 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9543 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9544 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
9545 ResultType->isSignedIntegerOrEnumerationType();
9546 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
9547 ResultType->isSignedIntegerOrEnumerationType();
9548 uint64_t LHSSize = LHS.getBitWidth();
9549 uint64_t RHSSize = RHS.getBitWidth();
9550 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
9551 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
9552
9553 // Add an additional bit if the signedness isn't uniformly agreed to. We
9554 // could do this ONLY if there is a signed and an unsigned that both have
9555 // MaxBits, but the code to check that is pretty nasty. The issue will be
9556 // caught in the shrink-to-result later anyway.
9557 if (IsSigned && !AllSigned)
9558 ++MaxBits;
9559
9560 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
9561 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
9562 Result = APSInt(MaxBits, !IsSigned);
9563 }
9564
9565 // Find largest int.
9566 switch (BuiltinOp) {
9567 default:
9568 llvm_unreachable("Invalid value for BuiltinOp");
9569 case Builtin::BI__builtin_add_overflow:
9570 case Builtin::BI__builtin_sadd_overflow:
9571 case Builtin::BI__builtin_saddl_overflow:
9572 case Builtin::BI__builtin_saddll_overflow:
9573 case Builtin::BI__builtin_uadd_overflow:
9574 case Builtin::BI__builtin_uaddl_overflow:
9575 case Builtin::BI__builtin_uaddll_overflow:
9576 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
9577 : LHS.uadd_ov(RHS, DidOverflow);
9578 break;
9579 case Builtin::BI__builtin_sub_overflow:
9580 case Builtin::BI__builtin_ssub_overflow:
9581 case Builtin::BI__builtin_ssubl_overflow:
9582 case Builtin::BI__builtin_ssubll_overflow:
9583 case Builtin::BI__builtin_usub_overflow:
9584 case Builtin::BI__builtin_usubl_overflow:
9585 case Builtin::BI__builtin_usubll_overflow:
9586 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
9587 : LHS.usub_ov(RHS, DidOverflow);
9588 break;
9589 case Builtin::BI__builtin_mul_overflow:
9590 case Builtin::BI__builtin_smul_overflow:
9591 case Builtin::BI__builtin_smull_overflow:
9592 case Builtin::BI__builtin_smulll_overflow:
9593 case Builtin::BI__builtin_umul_overflow:
9594 case Builtin::BI__builtin_umull_overflow:
9595 case Builtin::BI__builtin_umulll_overflow:
9596 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
9597 : LHS.umul_ov(RHS, DidOverflow);
9598 break;
9599 }
9600
9601 // In the case where multiple sizes are allowed, truncate and see if
9602 // the values are the same.
9603 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9604 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9605 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9606 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
9607 // since it will give us the behavior of a TruncOrSelf in the case where
9608 // its parameter <= its size. We previously set Result to be at least the
9609 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
9610 // will work exactly like TruncOrSelf.
9611 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
9612 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
9613
9614 if (!APSInt::isSameValue(Temp, Result))
9615 DidOverflow = true;
9616 Result = Temp;
9617 }
9618
9619 APValue APV{Result};
9620 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
9621 return false;
9622 return Success(DidOverflow, E);
9623 }
9624 }
9625}
9626
9627/// Determine whether this is a pointer past the end of the complete
9628/// object referred to by the lvalue.
9629static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
9630 const LValue &LV) {
9631 // A null pointer can be viewed as being "past the end" but we don't
9632 // choose to look at it that way here.
9633 if (!LV.getLValueBase())
9634 return false;
9635
9636 // If the designator is valid and refers to a subobject, we're not pointing
9637 // past the end.
9638 if (!LV.getLValueDesignator().Invalid &&
9639 !LV.getLValueDesignator().isOnePastTheEnd())
9640 return false;
9641
9642 // A pointer to an incomplete type might be past-the-end if the type's size is
9643 // zero. We cannot tell because the type is incomplete.
9644 QualType Ty = getType(LV.getLValueBase());
9645 if (Ty->isIncompleteType())
9646 return true;
9647
9648 // We're a past-the-end pointer if we point to the byte after the object,
9649 // no matter what our type or path is.
9650 auto Size = Ctx.getTypeSizeInChars(Ty);
9651 return LV.getLValueOffset() == Size;
9652}
9653
9654namespace {
9655
9656/// Data recursive integer evaluator of certain binary operators.
9657///
9658/// We use a data recursive algorithm for binary operators so that we are able
9659/// to handle extreme cases of chained binary operators without causing stack
9660/// overflow.
9661class DataRecursiveIntBinOpEvaluator {
9662 struct EvalResult {
9663 APValue Val;
9664 bool Failed;
9665
9666 EvalResult() : Failed(false) { }
9667
9668 void swap(EvalResult &RHS) {
9669 Val.swap(RHS.Val);
9670 Failed = RHS.Failed;
9671 RHS.Failed = false;
9672 }
9673 };
9674
9675 struct Job {
9676 const Expr *E;
9677 EvalResult LHSResult; // meaningful only for binary operator expression.
9678 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
9679
9680 Job() = default;
9681 Job(Job &&) = default;
9682
9683 void startSpeculativeEval(EvalInfo &Info) {
9684 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
9685 }
9686
9687 private:
9688 SpeculativeEvaluationRAII SpecEvalRAII;
9689 };
9690
9691 SmallVector<Job, 16> Queue;
9692
9693 IntExprEvaluator &IntEval;
9694 EvalInfo &Info;
9695 APValue &FinalResult;
9696
9697public:
9698 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
9699 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
9700
9701 /// True if \param E is a binary operator that we are going to handle
9702 /// data recursively.
9703 /// We handle binary operators that are comma, logical, or that have operands
9704 /// with integral or enumeration type.
9705 static bool shouldEnqueue(const BinaryOperator *E) {
9706 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
9707 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
9708 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
9709 E->getRHS()->getType()->isIntegralOrEnumerationType());
9710 }
9711
9712 bool Traverse(const BinaryOperator *E) {
9713 enqueue(E);
9714 EvalResult PrevResult;
9715 while (!Queue.empty())
9716 process(PrevResult);
9717
9718 if (PrevResult.Failed) return false;
9719
9720 FinalResult.swap(PrevResult.Val);
9721 return true;
9722 }
9723
9724private:
9725 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
9726 return IntEval.Success(Value, E, Result);
9727 }
9728 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
9729 return IntEval.Success(Value, E, Result);
9730 }
9731 bool Error(const Expr *E) {
9732 return IntEval.Error(E);
9733 }
9734 bool Error(const Expr *E, diag::kind D) {
9735 return IntEval.Error(E, D);
9736 }
9737
9738 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
9739 return Info.CCEDiag(E, D);
9740 }
9741
9742 // Returns true if visiting the RHS is necessary, false otherwise.
9743 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
9744 bool &SuppressRHSDiags);
9745
9746 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
9747 const BinaryOperator *E, APValue &Result);
9748
9749 void EvaluateExpr(const Expr *E, EvalResult &Result) {
9750 Result.Failed = !Evaluate(Result.Val, Info, E);
9751 if (Result.Failed)
9752 Result.Val = APValue();
9753 }
9754
9755 void process(EvalResult &Result);
9756
9757 void enqueue(const Expr *E) {
9758 E = E->IgnoreParens();
9759 Queue.resize(Queue.size()+1);
9760 Queue.back().E = E;
9761 Queue.back().Kind = Job::AnyExprKind;
9762 }
9763};
9764
9765}
9766
9767bool DataRecursiveIntBinOpEvaluator::
9768 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
9769 bool &SuppressRHSDiags) {
9770 if (E->getOpcode() == BO_Comma) {
9771 // Ignore LHS but note if we could not evaluate it.
9772 if (LHSResult.Failed)
9773 return Info.noteSideEffect();
9774 return true;
9775 }
9776
9777 if (E->isLogicalOp()) {
9778 bool LHSAsBool;
9779 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
9780 // We were able to evaluate the LHS, see if we can get away with not
9781 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
9782 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
9783 Success(LHSAsBool, E, LHSResult.Val);
9784 return false; // Ignore RHS
9785 }
9786 } else {
9787 LHSResult.Failed = true;
9788
9789 // Since we weren't able to evaluate the left hand side, it
9790 // might have had side effects.
9791 if (!Info.noteSideEffect())
9792 return false;
9793
9794 // We can't evaluate the LHS; however, sometimes the result
9795 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
9796 // Don't ignore RHS and suppress diagnostics from this arm.
9797 SuppressRHSDiags = true;
9798 }
9799
9800 return true;
9801 }
9802
9803 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
9804 E->getRHS()->getType()->isIntegralOrEnumerationType());
9805
9806 if (LHSResult.Failed && !Info.noteFailure())
9807 return false; // Ignore RHS;
9808
9809 return true;
9810}
9811
9812static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
9813 bool IsSub) {
9814 // Compute the new offset in the appropriate width, wrapping at 64 bits.
9815 // FIXME: When compiling for a 32-bit target, we should use 32-bit
9816 // offsets.
9817 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
9818 CharUnits &Offset = LVal.getLValueOffset();
9819 uint64_t Offset64 = Offset.getQuantity();
9820 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
9821 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
9822 : Offset64 + Index64);
9823}
9824
9825bool DataRecursiveIntBinOpEvaluator::
9826 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
9827 const BinaryOperator *E, APValue &Result) {
9828 if (E->getOpcode() == BO_Comma) {
9829 if (RHSResult.Failed)
9830 return false;
9831 Result = RHSResult.Val;
9832 return true;
9833 }
9834
9835 if (E->isLogicalOp()) {
9836 bool lhsResult, rhsResult;
9837 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
9838 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
9839
9840 if (LHSIsOK) {
9841 if (RHSIsOK) {
9842 if (E->getOpcode() == BO_LOr)
9843 return Success(lhsResult || rhsResult, E, Result);
9844 else
9845 return Success(lhsResult && rhsResult, E, Result);
9846 }
9847 } else {
9848 if (RHSIsOK) {
9849 // We can't evaluate the LHS; however, sometimes the result
9850 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
9851 if (rhsResult == (E->getOpcode() == BO_LOr))
9852 return Success(rhsResult, E, Result);
9853 }
9854 }
9855
9856 return false;
9857 }
9858
9859 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
9860 E->getRHS()->getType()->isIntegralOrEnumerationType());
9861
9862 if (LHSResult.Failed || RHSResult.Failed)
9863 return false;
9864
9865 const APValue &LHSVal = LHSResult.Val;
9866 const APValue &RHSVal = RHSResult.Val;
9867
9868 // Handle cases like (unsigned long)&a + 4.
9869 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
9870 Result = LHSVal;
9871 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
9872 return true;
9873 }
9874
9875 // Handle cases like 4 + (unsigned long)&a
9876 if (E->getOpcode() == BO_Add &&
9877 RHSVal.isLValue() && LHSVal.isInt()) {
9878 Result = RHSVal;
9879 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
9880 return true;
9881 }
9882
9883 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
9884 // Handle (intptr_t)&&A - (intptr_t)&&B.
9885 if (!LHSVal.getLValueOffset().isZero() ||
9886 !RHSVal.getLValueOffset().isZero())
9887 return false;
9888 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
9889 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
9890 if (!LHSExpr || !RHSExpr)
9891 return false;
9892 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9893 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9894 if (!LHSAddrExpr || !RHSAddrExpr)
9895 return false;
9896 // Make sure both labels come from the same function.
9897 if (LHSAddrExpr->getLabel()->getDeclContext() !=
9898 RHSAddrExpr->getLabel()->getDeclContext())
9899 return false;
9900 Result = APValue(LHSAddrExpr, RHSAddrExpr);
9901 return true;
9902 }
9903
9904 // All the remaining cases expect both operands to be an integer
9905 if (!LHSVal.isInt() || !RHSVal.isInt())
9906 return Error(E);
9907
9908 // Set up the width and signedness manually, in case it can't be deduced
9909 // from the operation we're performing.
9910 // FIXME: Don't do this in the cases where we can deduce it.
9911 APSInt Value(Info.Ctx.getIntRange(E->getType()),
9912 E->getType()->isUnsignedIntegerOrEnumerationType());
9913 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
9914 RHSVal.getInt(), Value))
9915 return false;
9916 return Success(Value, E, Result);
9917}
9918
9919void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
9920 Job &job = Queue.back();
9921
9922 switch (job.Kind) {
9923 case Job::AnyExprKind: {
9924 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
9925 if (shouldEnqueue(Bop)) {
9926 job.Kind = Job::BinOpKind;
9927 enqueue(Bop->getLHS());
9928 return;
9929 }
9930 }
9931
9932 EvaluateExpr(job.E, Result);
9933 Queue.pop_back();
9934 return;
9935 }
9936
9937 case Job::BinOpKind: {
9938 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
9939 bool SuppressRHSDiags = false;
9940 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
9941 Queue.pop_back();
9942 return;
9943 }
9944 if (SuppressRHSDiags)
9945 job.startSpeculativeEval(Info);
9946 job.LHSResult.swap(Result);
9947 job.Kind = Job::BinOpVisitedLHSKind;
9948 enqueue(Bop->getRHS());
9949 return;
9950 }
9951
9952 case Job::BinOpVisitedLHSKind: {
9953 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
9954 EvalResult RHS;
9955 RHS.swap(Result);
9956 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
9957 Queue.pop_back();
9958 return;
9959 }
9960 }
9961
9962 llvm_unreachable("Invalid Job::Kind!");
9963}
9964
9965namespace {
9966/// Used when we determine that we should fail, but can keep evaluating prior to
9967/// noting that we had a failure.
9968class DelayedNoteFailureRAII {
9969 EvalInfo &Info;
9970 bool NoteFailure;
9971
9972public:
9973 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
9974 : Info(Info), NoteFailure(NoteFailure) {}
9975 ~DelayedNoteFailureRAII() {
9976 if (NoteFailure) {
9977 bool ContinueAfterFailure = Info.noteFailure();
9978 (void)ContinueAfterFailure;
9979 assert(ContinueAfterFailure &&
9980 "Shouldn't have kept evaluating on failure.");
9981 }
9982 }
9983};
9984}
9985
9986template <class SuccessCB, class AfterCB>
9987static bool
9988EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
9989 SuccessCB &&Success, AfterCB &&DoAfter) {
9990 assert(E->isComparisonOp() && "expected comparison operator");
9991 assert((E->getOpcode() == BO_Cmp ||
9992 E->getType()->isIntegralOrEnumerationType()) &&
9993 "unsupported binary expression evaluation");
9994 auto Error = [&](const Expr *E) {
9995 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9996 return false;
9997 };
9998
9999 using CCR = ComparisonCategoryResult;
10000 bool IsRelational = E->isRelationalOp();
10001 bool IsEquality = E->isEqualityOp();
10002 if (E->getOpcode() == BO_Cmp) {
10003 const ComparisonCategoryInfo &CmpInfo =
10004 Info.Ctx.CompCategories.getInfoForType(E->getType());
10005 IsRelational = CmpInfo.isOrdered();
10006 IsEquality = CmpInfo.isEquality();
10007 }
10008
10009 QualType LHSTy = E->getLHS()->getType();
10010 QualType RHSTy = E->getRHS()->getType();
10011
10012 if (LHSTy->isIntegralOrEnumerationType() &&
10013 RHSTy->isIntegralOrEnumerationType()) {
10014 APSInt LHS, RHS;
10015 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
10016 if (!LHSOK && !Info.noteFailure())
10017 return false;
10018 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
10019 return false;
10020 if (LHS < RHS)
10021 return Success(CCR::Less, E);
10022 if (LHS > RHS)
10023 return Success(CCR::Greater, E);
10024 return Success(CCR::Equal, E);
10025 }
10026
10027 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
10028 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
10029 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
10030
10031 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
10032 if (!LHSOK && !Info.noteFailure())
10033 return false;
10034 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
10035 return false;
10036 if (LHSFX < RHSFX)
10037 return Success(CCR::Less, E);
10038 if (LHSFX > RHSFX)
10039 return Success(CCR::Greater, E);
10040 return Success(CCR::Equal, E);
10041 }
10042
10043 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
10044 ComplexValue LHS, RHS;
10045 bool LHSOK;
10046 if (E->isAssignmentOp()) {
10047 LValue LV;
10048 EvaluateLValue(E->getLHS(), LV, Info);
10049 LHSOK = false;
10050 } else if (LHSTy->isRealFloatingType()) {
10051 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
10052 if (LHSOK) {
10053 LHS.makeComplexFloat();
10054 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
10055 }
10056 } else {
10057 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
10058 }
10059 if (!LHSOK && !Info.noteFailure())
10060 return false;
10061
10062 if (E->getRHS()->getType()->isRealFloatingType()) {
10063 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
10064 return false;
10065 RHS.makeComplexFloat();
10066 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
10067 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
10068 return false;
10069
10070 if (LHS.isComplexFloat()) {
10071 APFloat::cmpResult CR_r =
10072 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
10073 APFloat::cmpResult CR_i =
10074 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
10075 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
10076 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
10077 } else {
10078 assert(IsEquality && "invalid complex comparison");
10079 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
10080 LHS.getComplexIntImag() == RHS.getComplexIntImag();
10081 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
10082 }
10083 }
10084
10085 if (LHSTy->isRealFloatingType() &&
10086 RHSTy->isRealFloatingType()) {
10087 APFloat RHS(0.0), LHS(0.0);
10088
10089 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
10090 if (!LHSOK && !Info.noteFailure())
10091 return false;
10092
10093 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
10094 return false;
10095
10096 assert(E->isComparisonOp() && "Invalid binary operator!");
10097 auto GetCmpRes = [&]() {
10098 switch (LHS.compare(RHS)) {
10099 case APFloat::cmpEqual:
10100 return CCR::Equal;
10101 case APFloat::cmpLessThan:
10102 return CCR::Less;
10103 case APFloat::cmpGreaterThan:
10104 return CCR::Greater;
10105 case APFloat::cmpUnordered:
10106 return CCR::Unordered;
10107 }
10108 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
10109 };
10110 return Success(GetCmpRes(), E);
10111 }
10112
10113 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
10114 LValue LHSValue, RHSValue;
10115
10116 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10117 if (!LHSOK && !Info.noteFailure())
10118 return false;
10119
10120 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10121 return false;
10122
10123 // Reject differing bases from the normal codepath; we special-case
10124 // comparisons to null.
10125 if (!HasSameBase(LHSValue, RHSValue)) {
10126 // Inequalities and subtractions between unrelated pointers have
10127 // unspecified or undefined behavior.
10128 if (!IsEquality)
10129 return Error(E);
10130 // A constant address may compare equal to the address of a symbol.
10131 // The one exception is that address of an object cannot compare equal
10132 // to a null pointer constant.
10133 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
10134 (!RHSValue.Base && !RHSValue.Offset.isZero()))
10135 return Error(E);
10136 // It's implementation-defined whether distinct literals will have
10137 // distinct addresses. In clang, the result of such a comparison is
10138 // unspecified, so it is not a constant expression. However, we do know
10139 // that the address of a literal will be non-null.
10140 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
10141 LHSValue.Base && RHSValue.Base)
10142 return Error(E);
10143 // We can't tell whether weak symbols will end up pointing to the same
10144 // object.
10145 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
10146 return Error(E);
10147 // We can't compare the address of the start of one object with the
10148 // past-the-end address of another object, per C++ DR1652.
10149 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
10150 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
10151 (RHSValue.Base && RHSValue.Offset.isZero() &&
10152 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
10153 return Error(E);
10154 // We can't tell whether an object is at the same address as another
10155 // zero sized object.
10156 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
10157 (LHSValue.Base && isZeroSized(RHSValue)))
10158 return Error(E);
10159 return Success(CCR::Nonequal, E);
10160 }
10161
10162 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10163 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10164
10165 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10166 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10167
10168 // C++11 [expr.rel]p3:
10169 // Pointers to void (after pointer conversions) can be compared, with a
10170 // result defined as follows: If both pointers represent the same
10171 // address or are both the null pointer value, the result is true if the
10172 // operator is <= or >= and false otherwise; otherwise the result is
10173 // unspecified.
10174 // We interpret this as applying to pointers to *cv* void.
10175 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
10176 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
10177
10178 // C++11 [expr.rel]p2:
10179 // - If two pointers point to non-static data members of the same object,
10180 // or to subobjects or array elements fo such members, recursively, the
10181 // pointer to the later declared member compares greater provided the
10182 // two members have the same access control and provided their class is
10183 // not a union.
10184 // [...]
10185 // - Otherwise pointer comparisons are unspecified.
10186 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
10187 bool WasArrayIndex;
10188 unsigned Mismatch = FindDesignatorMismatch(
10189 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
10190 // At the point where the designators diverge, the comparison has a
10191 // specified value if:
10192 // - we are comparing array indices
10193 // - we are comparing fields of a union, or fields with the same access
10194 // Otherwise, the result is unspecified and thus the comparison is not a
10195 // constant expression.
10196 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
10197 Mismatch < RHSDesignator.Entries.size()) {
10198 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
10199 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
10200 if (!LF && !RF)
10201 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
10202 else if (!LF)
10203 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
10204 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
10205 << RF->getParent() << RF;
10206 else if (!RF)
10207 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
10208 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
10209 << LF->getParent() << LF;
10210 else if (!LF->getParent()->isUnion() &&
10211 LF->getAccess() != RF->getAccess())
10212 Info.CCEDiag(E,
10213 diag::note_constexpr_pointer_comparison_differing_access)
10214 << LF << LF->getAccess() << RF << RF->getAccess()
10215 << LF->getParent();
10216 }
10217 }
10218
10219 // The comparison here must be unsigned, and performed with the same
10220 // width as the pointer offset.
10221#if 0 // Old code, should be equivalent to getIntRange
10222 auto &TI = Info.Ctx.getTargetInfo();
10223 unsigned AS = Info.Ctx.getTargetAddressSpace(
10224 LHSTy->getPointeeType().getAddressSpace());
10225 unsigned PtrSize = TI.getTypeWidth(TI.getPtrDiffType(AS));
10226#endif
10227 unsigned PtrSize = Info.Ctx.getIntRange(LHSTy);
10228 uint64_t CompareLHS = LHSOffset.getQuantity();
10229 uint64_t CompareRHS = RHSOffset.getQuantity();
10230 assert(PtrSize <= 64 && "Unexpected pointer width");
10231 uint64_t Mask = ~0ULL >> (64 - PtrSize);
10232 CompareLHS &= Mask;
10233 CompareRHS &= Mask;
10234
10235 // If there is a base and this is a relational operator, we can only
10236 // compare pointers within the object in question; otherwise, the result
10237 // depends on where the object is located in memory.
10238 if (!LHSValue.Base.isNull() && IsRelational) {
10239 QualType BaseTy = getType(LHSValue.Base);
10240 if (BaseTy->isIncompleteType())
10241 return Error(E);
10242 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
10243 uint64_t OffsetLimit = Size.getQuantity();
10244 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
10245 return Error(E);
10246 }
10247
10248 if (CompareLHS < CompareRHS)
10249 return Success(CCR::Less, E);
10250 if (CompareLHS > CompareRHS)
10251 return Success(CCR::Greater, E);
10252 return Success(CCR::Equal, E);
10253 }
10254
10255 if (LHSTy->isMemberPointerType()) {
10256 assert(IsEquality && "unexpected member pointer operation");
10257 assert(RHSTy->isMemberPointerType() && "invalid comparison");
10258
10259 MemberPtr LHSValue, RHSValue;
10260
10261 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
10262 if (!LHSOK && !Info.noteFailure())
10263 return false;
10264
10265 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10266 return false;
10267
10268 // C++11 [expr.eq]p2:
10269 // If both operands are null, they compare equal. Otherwise if only one is
10270 // null, they compare unequal.
10271 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
10272 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
10273 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
10274 }
10275
10276 // Otherwise if either is a pointer to a virtual member function, the
10277 // result is unspecified.
10278 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
10279 if (MD->isVirtual())
10280 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
10281 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
10282 if (MD->isVirtual())
10283 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
10284
10285 // Otherwise they compare equal if and only if they would refer to the
10286 // same member of the same most derived object or the same subobject if
10287 // they were dereferenced with a hypothetical object of the associated
10288 // class type.
10289 bool Equal = LHSValue == RHSValue;
10290 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
10291 }
10292
10293 if (LHSTy->isNullPtrType()) {
10294 assert(E->isComparisonOp() && "unexpected nullptr operation");
10295 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
10296 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
10297 // are compared, the result is true of the operator is <=, >= or ==, and
10298 // false otherwise.
10299 return Success(CCR::Equal, E);
10300 }
10301
10302 return DoAfter();
10303}
10304
10305bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
10306 if (!CheckLiteralType(Info, E))
10307 return false;
10308
10309 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10310 const BinaryOperator *E) {
10311 // Evaluation succeeded. Lookup the information for the comparison category
10312 // type and fetch the VarDecl for the result.
10313 const ComparisonCategoryInfo &CmpInfo =
10314 Info.Ctx.CompCategories.getInfoForType(E->getType());
10315 const VarDecl *VD =
10316 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
10317 // Check and evaluate the result as a constant expression.
10318 LValue LV;
10319 LV.set(VD);
10320 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10321 return false;
10322 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10323 };
10324 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10325 return ExprEvaluatorBaseTy::VisitBinCmp(E);
10326 });
10327}
10328
10329bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10330 // We don't call noteFailure immediately because the assignment happens after
10331 // we evaluate LHS and RHS.
10332 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
10333 return Error(E);
10334
10335 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
10336 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
10337 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
10338
10339 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
10340 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
10341 "DataRecursiveIntBinOpEvaluator should have handled integral types");
10342
10343 if (E->isComparisonOp()) {
10344 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
10345 // comparisons and then translating the result.
10346 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10347 const BinaryOperator *E) {
10348 using CCR = ComparisonCategoryResult;
10349 bool IsEqual = ResKind == CCR::Equal,
10350 IsLess = ResKind == CCR::Less,
10351 IsGreater = ResKind == CCR::Greater;
10352 auto Op = E->getOpcode();
10353 switch (Op) {
10354 default:
10355 llvm_unreachable("unsupported binary operator");
10356 case BO_EQ:
10357 case BO_NE:
10358 return Success(IsEqual == (Op == BO_EQ), E);
10359 case BO_LT: return Success(IsLess, E);
10360 case BO_GT: return Success(IsGreater, E);
10361 case BO_LE: return Success(IsEqual || IsLess, E);
10362 case BO_GE: return Success(IsEqual || IsGreater, E);
10363 }
10364 };
10365 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10366 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10367 });
10368 }
10369
10370 QualType LHSTy = E->getLHS()->getType();
10371 QualType RHSTy = E->getRHS()->getType();
10372
10373 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
10374 E->getOpcode() == BO_Sub) {
10375 LValue LHSValue, RHSValue;
10376
10377 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10378 if (!LHSOK && !Info.noteFailure())
10379 return false;
10380
10381 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10382 return false;
10383
10384 // Reject differing bases from the normal codepath; we special-case
10385 // comparisons to null.
10386 if (!HasSameBase(LHSValue, RHSValue)) {
10387 // Handle &&A - &&B.
10388 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
10389 return Error(E);
10390 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
10391 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
10392 if (!LHSExpr || !RHSExpr)
10393 return Error(E);
10394 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10395 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10396 if (!LHSAddrExpr || !RHSAddrExpr)
10397 return Error(E);
10398 // Make sure both labels come from the same function.
10399 if (LHSAddrExpr->getLabel()->getDeclContext() !=
10400 RHSAddrExpr->getLabel()->getDeclContext())
10401 return Error(E);
10402 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
10403 }
10404 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10405 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10406
10407 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10408 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10409
10410 // C++11 [expr.add]p6:
10411 // Unless both pointers point to elements of the same array object, or
10412 // one past the last element of the array object, the behavior is
10413 // undefined.
10414 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
10415 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
10416 RHSDesignator))
10417 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
10418
10419 QualType Type = E->getLHS()->getType();
10420 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
10421
10422 CharUnits ElementSize;
10423 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
10424 return false;
10425
10426 // As an extension, a type may have zero size (empty struct or union in
10427 // C, array of zero length). Pointer subtraction in such cases has
10428 // undefined behavior, so is not constant.
10429 if (ElementSize.isZero()) {
10430 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
10431 << ElementType;
10432 return false;
10433 }
10434
10435 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
10436 // and produce incorrect results when it overflows. Such behavior
10437 // appears to be non-conforming, but is common, so perhaps we should
10438 // assume the standard intended for such cases to be undefined behavior
10439 // and check for them.
10440
10441 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
10442 // overflow in the final conversion to ptrdiff_t.
10443 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
10444 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
10445 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
10446 false);
10447 APSInt TrueResult = (LHS - RHS) / ElemSize;
10448 APSInt Result = TrueResult.trunc(Info.Ctx.getIntRange(E->getType()));
10449
10450 if (Result.extend(65) != TrueResult &&
10451 !HandleOverflow(Info, E, TrueResult, E->getType()))
10452 return false;
10453 return Success(Result, E);
10454 }
10455
10456 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10457}
10458
10459/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
10460/// a result as the expression's type.
10461bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
10462 const UnaryExprOrTypeTraitExpr *E) {
10463 switch(E->getKind()) {
10464 case UETT_PreferredAlignOf:
10465 case UETT_AlignOf: {
10466 if (E->isArgumentType())
10467 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
10468 E);
10469 else
10470 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
10471 E);
10472 }
10473
10474 case UETT_VecStep: {
10475 QualType Ty = E->getTypeOfArgument();
10476
10477 if (Ty->isVectorType()) {
10478 unsigned n = Ty->castAs<VectorType>()->getNumElements();
10479
10480 // The vec_step built-in functions that take a 3-component
10481 // vector return 4. (OpenCL 1.1 spec 6.11.12)
10482 if (n == 3)
10483 n = 4;
10484
10485 return Success(n, E);
10486 } else
10487 return Success(1, E);
10488 }
10489
10490 case UETT_SizeOf: {
10491 QualType SrcTy = E->getTypeOfArgument();
10492 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
10493 // the result is the size of the referenced type."
10494 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
10495 SrcTy = Ref->getPointeeType();
10496
10497 CharUnits Sizeof;
10498 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
10499 return false;
10500 return Success(Sizeof, E);
10501 }
10502 case UETT_OpenMPRequiredSimdAlign:
10503 assert(E->isArgumentType());
10504 return Success(
10505 Info.Ctx.toCharUnitsFromBits(
10506 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
10507 .getQuantity(),
10508 E);
10509 }
10510
10511 llvm_unreachable("unknown expr/type trait");
10512}
10513
10514bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
10515 CharUnits Result;
10516 unsigned n = OOE->getNumComponents();
10517 if (n == 0)
10518 return Error(OOE);
10519 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
10520 for (unsigned i = 0; i != n; ++i) {
10521 OffsetOfNode ON = OOE->getComponent(i);
10522 switch (ON.getKind()) {
10523 case OffsetOfNode::Array: {
10524 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
10525 APSInt IdxResult;
10526 if (!EvaluateInteger(Idx, IdxResult, Info))
10527 return false;
10528 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
10529 if (!AT)
10530 return Error(OOE);
10531 CurrentType = AT->getElementType();
10532 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
10533 Result += IdxResult.getSExtValue() * ElementSize;
10534 break;
10535 }
10536
10537 case OffsetOfNode::Field: {
10538 FieldDecl *MemberDecl = ON.getField();
10539 const RecordType *RT = CurrentType->getAs<RecordType>();
10540 if (!RT)
10541 return Error(OOE);
10542 RecordDecl *RD = RT->getDecl();
10543 if (RD->isInvalidDecl()) return false;
10544 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10545 unsigned i = MemberDecl->getFieldIndex();
10546 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
10547 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
10548 CurrentType = MemberDecl->getType().getNonReferenceType();
10549 break;
10550 }
10551
10552 case OffsetOfNode::Identifier:
10553 llvm_unreachable("dependent __builtin_offsetof");
10554
10555 case OffsetOfNode::Base: {
10556 CXXBaseSpecifier *BaseSpec = ON.getBase();
10557 if (BaseSpec->isVirtual())
10558 return Error(OOE);
10559
10560 // Find the layout of the class whose base we are looking into.
10561 const RecordType *RT = CurrentType->getAs<RecordType>();
10562 if (!RT)
10563 return Error(OOE);
10564 RecordDecl *RD = RT->getDecl();
10565 if (RD->isInvalidDecl()) return false;
10566 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10567
10568 // Find the base class itself.
10569 CurrentType = BaseSpec->getType();
10570 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
10571 if (!BaseRT)
10572 return Error(OOE);
10573
10574 // Add the offset to the base.
10575 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
10576 break;
10577 }
10578 }
10579 }
10580 return Success(Result, OOE);
10581}
10582
10583bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10584 switch (E->getOpcode()) {
10585 default:
10586 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
10587 // See C99 6.6p3.
10588 return Error(E);
10589 case UO_Extension:
10590 // FIXME: Should extension allow i-c-e extension expressions in its scope?
10591 // If so, we could clear the diagnostic ID.
10592 return Visit(E->getSubExpr());
10593 case UO_Plus:
10594 // The result is just the value.
10595 return Visit(E->getSubExpr());
10596 case UO_Minus: {
10597 if (!Visit(E->getSubExpr()))
10598 return false;
10599 if (!Result.isInt()) return Error(E);
10600 const APSInt &Value = Result.getInt();
10601 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
10602 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
10603 E->getType()))
10604 return false;
10605 return Success(-Value, E);
10606 }
10607 case UO_Not: {
10608 if (!Visit(E->getSubExpr()))
10609 return false;
10610 if (!Result.isInt()) return Error(E);
10611 return Success(~Result.getInt(), E);
10612 }
10613 case UO_LNot: {
10614 bool bres;
10615 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
10616 return false;
10617 return Success(!bres, E);
10618 }
10619 }
10620}
10621
10622/// HandleCast - This is used to evaluate implicit or explicit casts where the
10623/// result type is integer.
10624bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
10625 const Expr *SubExpr = E->getSubExpr();
10626 QualType DestType = E->getType();
10627 QualType SrcType = SubExpr->getType();
10628
10629 switch (E->getCastKind()) {
10630 case CK_BaseToDerived:
10631 case CK_DerivedToBase:
10632 case CK_UncheckedDerivedToBase:
10633 case CK_Dynamic:
10634 case CK_ToUnion:
10635 case CK_ArrayToPointerDecay:
10636 case CK_FunctionToPointerDecay:
10637 case CK_NullToPointer:
10638 case CK_NullToMemberPointer:
10639 case CK_BaseToDerivedMemberPointer:
10640 case CK_DerivedToBaseMemberPointer:
10641 case CK_ReinterpretMemberPointer:
10642 case CK_ConstructorConversion:
10643 case CK_IntegralToPointer:
10644 case CK_ToVoid:
10645 case CK_VectorSplat:
10646 case CK_IntegralToFloating:
10647 case CK_FloatingCast:
10648 case CK_CPointerToObjCPointerCast:
10649 case CK_BlockPointerToObjCPointerCast:
10650 case CK_AnyPointerToBlockPointerCast:
10651 case CK_ObjCObjectLValueCast:
10652 case CK_FloatingRealToComplex:
10653 case CK_FloatingComplexToReal:
10654 case CK_FloatingComplexCast:
10655 case CK_FloatingComplexToIntegralComplex:
10656 case CK_IntegralRealToComplex:
10657 case CK_IntegralComplexCast:
10658 case CK_IntegralComplexToFloatingComplex:
10659 case CK_BuiltinFnToFnPtr:
10660 case CK_ZeroToOCLOpaqueType:
10661 case CK_NonAtomicToAtomic:
10662 case CK_AddressSpaceConversion:
10663 case CK_CHERICapabilityToPointer:
10664 case CK_PointerToCHERICapability:
10665 case CK_IntToOCLSampler:
10666 case CK_FixedPointCast:
10667 case CK_IntegralToFixedPoint:
10668 llvm_unreachable("invalid cast kind for integral value");
10669
10670 case CK_BitCast:
10671 case CK_Dependent:
10672 case CK_LValueBitCast:
10673 case CK_ARCProduceObject:
10674 case CK_ARCConsumeObject:
10675 case CK_ARCReclaimReturnedObject:
10676 case CK_ARCExtendBlockObject:
10677 case CK_CopyAndAutoreleaseBlockObject:
10678 return Error(E);
10679
10680 case CK_UserDefinedConversion:
10681 case CK_LValueToRValue:
10682 case CK_AtomicToNonAtomic:
10683 case CK_NoOp:
10684 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10685
10686 case CK_CHERICapabilityToOffset:
10687 case CK_CHERICapabilityToAddress: {
10688 // We only seem to get here if we are casting the result of the
10689 // __cheri_{offset, addr} cast to an integer type different to what was
10690 // specified as part of the CHERI cast. We return true here to report
10691 // that these casts have an integer value. Typechecking will have been
10692 // performed earlier.
10693 return true;
10694 }
10695
10696 case CK_MemberPointerToBoolean:
10697 case CK_PointerToBoolean:
10698 case CK_IntegralToBoolean:
10699 case CK_FloatingToBoolean:
10700 case CK_BooleanToSignedIntegral:
10701 case CK_FloatingComplexToBoolean:
10702 case CK_IntegralComplexToBoolean: {
10703 bool BoolResult;
10704 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
10705 return false;
10706 uint64_t IntResult = BoolResult;
10707 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
10708 IntResult = (uint64_t)-1;
10709 return Success(IntResult, E);
10710 }
10711
10712 case CK_FixedPointToIntegral: {
10713 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
10714 if (!EvaluateFixedPoint(SubExpr, Src, Info))
10715 return false;
10716 bool Overflowed;
10717 llvm::APSInt Result = Src.convertToInt(
10718 Info.Ctx.getIntRange(DestType),
10719 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
10720 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
10721 return false;
10722 return Success(Result, E);
10723 }
10724
10725 case CK_FixedPointToBoolean: {
10726 // Unsigned padding does not affect this.
10727 APValue Val;
10728 if (!Evaluate(Val, Info, SubExpr))
10729 return false;
10730 return Success(Val.getFixedPoint().getBoolValue(), E);
10731 }
10732
10733 case CK_IntegralCast: {
10734 if (!Visit(SubExpr))
10735 return false;
10736
10737 if (!Result.isInt()) {
10738 // Allow casts of address-of-label differences if they are no-ops
10739 // or narrowing. (The narrowing case isn't actually guaranteed to
10740 // be constant-evaluatable except in some narrow cases which are hard
10741 // to detect here. We let it through on the assumption the user knows
10742 // what they are doing.)
10743 if (Result.isAddrLabelDiff())
10744 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
10745 // CHERI: If we are doing an integer cast from a capability, then extract
10746 // the int value
10747 if (SrcType->isIntCapType()) {
10748 Expr::EvalResult ExprResult;
10749 if (!SubExpr->EvaluateAsInt(ExprResult, Info.Ctx))
10750 return false;
10751 ExprResult.Val.getInt().setIsUnsigned(SrcType->isUnsignedIntegerOrEnumerationType());
10752 Result = ExprResult.Val;
10753 } else
10754 // Only allow casts of lvalues if they are lossless.
10755 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
10756 }
10757
10758 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
10759 Result.getInt()), E);
10760 }
10761
10762 case CK_PointerToIntegral: {
10763 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
10764
10765 LValue LV;
10766 if (!EvaluatePointer(SubExpr, LV, Info))
10767 return false;
10768
10769 if (LV.getLValueBase()) {
10770 // Only allow based lvalue casts if they are lossless.
10771 // FIXME: Allow a larger integer size than the pointer size, and allow
10772 // narrowing back down to pointer width in subsequent integral casts.
10773 // FIXME: Check integer type's active bits, not its type size.
10774 uint64_t DestUsableBits = Info.Ctx.getTypeSize(DestType);
10775 uint64_t SrcBits = Info.Ctx.getTypeSize(SrcType);
10776
10777
10778 // XXXAR: In C the only way to silence -Wcast-qual is by casting via a uintptr_t
10779 // This happens e.g. in the FreeBSD __DECONST/__DEVOLATILE macros so we need to
10780 // allow that case
10781 if (DestType->isCHERICapabilityType(Info.Ctx)) {
10782 DestUsableBits = Info.Ctx.getTargetInfo().getPointerRangeForCHERICapability();
10783 }
10784 if (SrcType->isCHERICapabilityType(Info.Ctx)) {
10785 SrcBits = Info.Ctx.getTargetInfo().getPointerRangeForCHERICapability();
10786 }
10787 // XXXAR: There should be a more useful diagnostic here
10788 if (DestUsableBits != SrcBits)
10789 return Error(E);
10790
10791 LV.Designator.setInvalid();
10792 LV.moveInto(Result);
10793 return true;
10794 }
10795
10796 APSInt AsInt;
10797 APValue V;
10798 LV.moveInto(V);
10799 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
10800 llvm_unreachable("Can't cast this!");
10801
10802 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
10803 }
10804
10805 case CK_IntegralComplexToReal: {
10806 ComplexValue C;
10807 if (!EvaluateComplex(SubExpr, C, Info))
10808 return false;
10809 return Success(C.getComplexIntReal(), E);
10810 }
10811
10812 case CK_FloatingToIntegral: {
10813 APFloat F(0.0);
10814 if (!EvaluateFloat(SubExpr, F, Info))
10815 return false;
10816
10817 APSInt Value;
10818 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
10819 return false;
10820 return Success(Value, E);
10821 }
10822 }
10823
10824 llvm_unreachable("unknown cast resulting in integral value");
10825}
10826
10827bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
10828 if (E->getSubExpr()->getType()->isAnyComplexType()) {
10829 ComplexValue LV;
10830 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
10831 return false;
10832 if (!LV.isComplexInt())
10833 return Error(E);
10834 return Success(LV.getComplexIntReal(), E);
10835 }
10836
10837 return Visit(E->getSubExpr());
10838}
10839
10840bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10841 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
10842 ComplexValue LV;
10843 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
10844 return false;
10845 if (!LV.isComplexInt())
10846 return Error(E);
10847 return Success(LV.getComplexIntImag(), E);
10848 }
10849
10850 VisitIgnoredValue(E->getSubExpr());
10851 return Success(0, E);
10852}
10853
10854bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
10855 return Success(E->getPackLength(), E);
10856}
10857
10858bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
10859 return Success(E->getValue(), E);
10860}
10861
10862bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10863 switch (E->getOpcode()) {
10864 default:
10865 // Invalid unary operators
10866 return Error(E);
10867 case UO_Plus:
10868 // The result is just the value.
10869 return Visit(E->getSubExpr());
10870 case UO_Minus: {
10871 if (!Visit(E->getSubExpr())) return false;
10872 if (!Result.isFixedPoint())
10873 return Error(E);
10874 bool Overflowed;
10875 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
10876 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
10877 return false;
10878 return Success(Negated, E);
10879 }
10880 case UO_LNot: {
10881 bool bres;
10882 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
10883 return false;
10884 return Success(!bres, E);
10885 }
10886 }
10887}
10888
10889bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
10890 const Expr *SubExpr = E->getSubExpr();
10891 QualType DestType = E->getType();
10892 assert(DestType->isFixedPointType() &&
10893 "Expected destination type to be a fixed point type");
10894 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
10895
10896 switch (E->getCastKind()) {
10897 case CK_FixedPointCast: {
10898 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
10899 if (!EvaluateFixedPoint(SubExpr, Src, Info))
10900 return false;
10901 bool Overflowed;
10902 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
10903 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
10904 return false;
10905 return Success(Result, E);
10906 }
10907 case CK_IntegralToFixedPoint: {
10908 APSInt Src;
10909 if (!EvaluateInteger(SubExpr, Src, Info))
10910 return false;
10911
10912 bool Overflowed;
10913 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
10914 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
10915
10916 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
10917 return false;
10918
10919 return Success(IntResult, E);
10920 }
10921 case CK_NoOp:
10922 case CK_LValueToRValue:
10923 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10924 default:
10925 return Error(E);
10926 }
10927}
10928
10929bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10930 const Expr *LHS = E->getLHS();
10931 const Expr *RHS = E->getRHS();
10932 FixedPointSemantics ResultFXSema =
10933 Info.Ctx.getFixedPointSemantics(E->getType());
10934
10935 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
10936 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
10937 return false;
10938 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
10939 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
10940 return false;
10941
10942 switch (E->getOpcode()) {
10943 case BO_Add: {
10944 bool AddOverflow, ConversionOverflow;
10945 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
10946 .convert(ResultFXSema, &ConversionOverflow);
10947 if ((AddOverflow || ConversionOverflow) &&
10948 !HandleOverflow(Info, E, Result, E->getType()))
10949 return false;
10950 return Success(Result, E);
10951 }
10952 default:
10953 return false;
10954 }
10955 llvm_unreachable("Should've exited before this");
10956}
10957
10958//===----------------------------------------------------------------------===//
10959// Float Evaluation
10960//===----------------------------------------------------------------------===//
10961
10962namespace {
10963class FloatExprEvaluator
10964 : public ExprEvaluatorBase<FloatExprEvaluator> {
10965 APFloat &Result;
10966public:
10967 FloatExprEvaluator(EvalInfo &info, APFloat &result)
10968 : ExprEvaluatorBaseTy(info), Result(result) {}
10969
10970 bool Success(const APValue &V, const Expr *e) {
10971 Result = V.getFloat();
10972 return true;
10973 }
10974
10975 bool ZeroInitialization(const Expr *E) {
10976 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
10977 return true;
10978 }
10979
10980 bool VisitCallExpr(const CallExpr *E);
10981
10982 bool VisitUnaryOperator(const UnaryOperator *E);
10983 bool VisitBinaryOperator(const BinaryOperator *E);
10984 bool VisitFloatingLiteral(const FloatingLiteral *E);
10985 bool VisitCastExpr(const CastExpr *E);
10986
10987 bool VisitUnaryReal(const UnaryOperator *E);
10988 bool VisitUnaryImag(const UnaryOperator *E);
10989
10990 // FIXME: Missing: array subscript of vector, member of vector
10991};
10992} // end anonymous namespace
10993
10994static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
10995 assert(E->isRValue() && E->getType()->isRealFloatingType());
10996 return FloatExprEvaluator(Info, Result).Visit(E);
10997}
10998
10999static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
11000 QualType ResultTy,
11001 const Expr *Arg,
11002 bool SNaN,
11003 llvm::APFloat &Result) {
11004 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
11005 if (!S) return false;
11006
11007 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
11008
11009 llvm::APInt fill;
11010
11011 // Treat empty strings as if they were zero.
11012 if (S->getString().empty())
11013 fill = llvm::APInt(32, 0);
11014 else if (S->getString().getAsInteger(0, fill))
11015 return false;
11016
11017 if (Context.getTargetInfo().isNan2008()) {
11018 if (SNaN)
11019 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11020 else
11021 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11022 } else {
11023 // Prior to IEEE 754-2008, architectures were allowed to choose whether
11024 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
11025 // a different encoding to what became a standard in 2008, and for pre-
11026 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
11027 // sNaN. This is now known as "legacy NaN" encoding.
11028 if (SNaN)
11029 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11030 else
11031 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11032 }
11033
11034 return true;
11035}
11036
11037bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
11038 switch (E->getBuiltinCallee()) {
11039 default:
11040 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11041
11042 case Builtin::BI__builtin_huge_val:
11043 case Builtin::BI__builtin_huge_valf:
11044 case Builtin::BI__builtin_huge_vall:
11045 case Builtin::BI__builtin_huge_valf128:
11046 case Builtin::BI__builtin_inf:
11047 case Builtin::BI__builtin_inff:
11048 case Builtin::BI__builtin_infl:
11049 case Builtin::BI__builtin_inff128: {
11050 const llvm::fltSemantics &Sem =
11051 Info.Ctx.getFloatTypeSemantics(E->getType());
11052 Result = llvm::APFloat::getInf(Sem);
11053 return true;
11054 }
11055
11056 case Builtin::BI__builtin_nans:
11057 case Builtin::BI__builtin_nansf:
11058 case Builtin::BI__builtin_nansl:
11059 case Builtin::BI__builtin_nansf128:
11060 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11061 true, Result))
11062 return Error(E);
11063 return true;
11064
11065 case Builtin::BI__builtin_nan:
11066 case Builtin::BI__builtin_nanf:
11067 case Builtin::BI__builtin_nanl:
11068 case Builtin::BI__builtin_nanf128:
11069 // If this is __builtin_nan() turn this into a nan, otherwise we
11070 // can't constant fold it.
11071 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11072 false, Result))
11073 return Error(E);
11074 return true;
11075
11076 case Builtin::BI__builtin_fabs:
11077 case Builtin::BI__builtin_fabsf:
11078 case Builtin::BI__builtin_fabsl:
11079 case Builtin::BI__builtin_fabsf128:
11080 if (!EvaluateFloat(E->getArg(0), Result, Info))
11081 return false;
11082
11083 if (Result.isNegative())
11084 Result.changeSign();
11085 return true;
11086
11087 // FIXME: Builtin::BI__builtin_powi
11088 // FIXME: Builtin::BI__builtin_powif
11089 // FIXME: Builtin::BI__builtin_powil
11090
11091 case Builtin::BI__builtin_copysign:
11092 case Builtin::BI__builtin_copysignf:
11093 case Builtin::BI__builtin_copysignl:
11094 case Builtin::BI__builtin_copysignf128: {
11095 APFloat RHS(0.);
11096 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
11097 !EvaluateFloat(E->getArg(1), RHS, Info))
11098 return false;
11099 Result.copySign(RHS);
11100 return true;
11101 }
11102 }
11103}
11104
11105bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
11106 if (E->getSubExpr()->getType()->isAnyComplexType()) {
11107 ComplexValue CV;
11108 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11109 return false;
11110 Result = CV.FloatReal;
11111 return true;
11112 }
11113
11114 return Visit(E->getSubExpr());
11115}
11116
11117bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11118 if (E->getSubExpr()->getType()->isAnyComplexType()) {
11119 ComplexValue CV;
11120 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11121 return false;
11122 Result = CV.FloatImag;
11123 return true;
11124 }
11125
11126 VisitIgnoredValue(E->getSubExpr());
11127 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
11128 Result = llvm::APFloat::getZero(Sem);
11129 return true;
11130}
11131
11132bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11133 switch (E->getOpcode()) {
11134 default: return Error(E);
11135 case UO_Plus:
11136 return EvaluateFloat(E->getSubExpr(), Result, Info);
11137 case UO_Minus:
11138 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
11139 return false;
11140 Result.changeSign();
11141 return true;
11142 }
11143}
11144
11145bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11146 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11147 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11148
11149 APFloat RHS(0.0);
11150 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
11151 if (!LHSOK && !Info.noteFailure())
11152 return false;
11153 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
11154 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
11155}
11156
11157bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
11158 Result = E->getValue();
11159 return true;
11160}
11161
11162bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
11163 const Expr* SubExpr = E->getSubExpr();
11164
11165 switch (E->getCastKind()) {
11166 default:
11167 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11168
11169 case CK_IntegralToFloating: {
11170 APSInt IntResult;
11171 return EvaluateInteger(SubExpr, IntResult, Info) &&
11172 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
11173 E->getType(), Result);
11174 }
11175
11176 case CK_FloatingCast: {
11177 if (!Visit(SubExpr))
11178 return false;
11179 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
11180 Result);
11181 }
11182
11183 case CK_FloatingComplexToReal: {
11184 ComplexValue V;
11185 if (!EvaluateComplex(SubExpr, V, Info))
11186 return false;
11187 Result = V.getComplexFloatReal();
11188 return true;
11189 }
11190 }
11191}
11192
11193//===----------------------------------------------------------------------===//
11194// Complex Evaluation (for float and integer)
11195//===----------------------------------------------------------------------===//
11196
11197namespace {
11198class ComplexExprEvaluator
11199 : public ExprEvaluatorBase<ComplexExprEvaluator> {
11200 ComplexValue &Result;
11201
11202public:
11203 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
11204 : ExprEvaluatorBaseTy(info), Result(Result) {}
11205
11206 bool Success(const APValue &V, const Expr *e) {
11207 Result.setFrom(V);
11208 return true;
11209 }
11210
11211 bool ZeroInitialization(const Expr *E);
11212
11213 //===--------------------------------------------------------------------===//
11214 // Visitor Methods
11215 //===--------------------------------------------------------------------===//
11216
11217 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
11218 bool VisitCastExpr(const CastExpr *E);
11219 bool VisitBinaryOperator(const BinaryOperator *E);
11220 bool VisitUnaryOperator(const UnaryOperator *E);
11221 bool VisitInitListExpr(const InitListExpr *E);
11222};
11223} // end anonymous namespace
11224
11225static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
11226 EvalInfo &Info) {
11227 assert(E->isRValue() && E->getType()->isAnyComplexType());
11228 return ComplexExprEvaluator(Info, Result).Visit(E);
11229}
11230
11231bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
11232 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
11233 if (ElemTy->isRealFloatingType()) {
11234 Result.makeComplexFloat();
11235 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
11236 Result.FloatReal = Zero;
11237 Result.FloatImag = Zero;
11238 } else {
11239 Result.makeComplexInt();
11240 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
11241 Result.IntReal = Zero;
11242 Result.IntImag = Zero;
11243 }
11244 return true;
11245}
11246
11247bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
11248 const Expr* SubExpr = E->getSubExpr();
11249
11250 if (SubExpr->getType()->isRealFloatingType()) {
11251 Result.makeComplexFloat();
11252 APFloat &Imag = Result.FloatImag;
11253 if (!EvaluateFloat(SubExpr, Imag, Info))
11254 return false;
11255
11256 Result.FloatReal = APFloat(Imag.getSemantics());
11257 return true;
11258 } else {
11259 assert(SubExpr->getType()->isIntegerType() &&
11260 "Unexpected imaginary literal.");
11261
11262 Result.makeComplexInt();
11263 APSInt &Imag = Result.IntImag;
11264 if (!EvaluateInteger(SubExpr, Imag, Info))
11265 return false;
11266
11267 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
11268 return true;
11269 }
11270}
11271
11272bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
11273
11274 switch (E->getCastKind()) {
11275 case CK_BitCast:
11276 case CK_BaseToDerived:
11277 case CK_DerivedToBase:
11278 case CK_UncheckedDerivedToBase:
11279 case CK_Dynamic:
11280 case CK_ToUnion:
11281 case CK_ArrayToPointerDecay:
11282 case CK_FunctionToPointerDecay:
11283 case CK_NullToPointer:
11284 case CK_NullToMemberPointer:
11285 case CK_BaseToDerivedMemberPointer:
11286 case CK_DerivedToBaseMemberPointer:
11287 case CK_MemberPointerToBoolean:
11288 case CK_ReinterpretMemberPointer:
11289 case CK_ConstructorConversion:
11290 case CK_IntegralToPointer:
11291 case CK_PointerToIntegral:
11292 case CK_PointerToBoolean:
11293 case CK_ToVoid:
11294 case CK_VectorSplat:
11295 case CK_IntegralCast:
11296 case CK_BooleanToSignedIntegral:
11297 case CK_IntegralToBoolean:
11298 case CK_IntegralToFloating:
11299 case CK_FloatingToIntegral:
11300 case CK_FloatingToBoolean:
11301 case CK_FloatingCast:
11302 case CK_CPointerToObjCPointerCast:
11303 case CK_BlockPointerToObjCPointerCast:
11304 case CK_AnyPointerToBlockPointerCast:
11305 case CK_ObjCObjectLValueCast:
11306 case CK_FloatingComplexToReal:
11307 case CK_FloatingComplexToBoolean:
11308 case CK_IntegralComplexToReal:
11309 case CK_IntegralComplexToBoolean:
11310 case CK_ARCProduceObject:
11311 case CK_ARCConsumeObject:
11312 case CK_ARCReclaimReturnedObject:
11313 case CK_ARCExtendBlockObject:
11314 case CK_CopyAndAutoreleaseBlockObject:
11315 case CK_BuiltinFnToFnPtr:
11316 case CK_ZeroToOCLOpaqueType:
11317 case CK_NonAtomicToAtomic:
11318 case CK_AddressSpaceConversion:
11319 case CK_CHERICapabilityToPointer:
11320 case CK_PointerToCHERICapability:
11321 case CK_CHERICapabilityToOffset:
11322 case CK_CHERICapabilityToAddress:
11323 case CK_IntToOCLSampler:
11324 case CK_FixedPointCast:
11325 case CK_FixedPointToBoolean:
11326 case CK_FixedPointToIntegral:
11327 case CK_IntegralToFixedPoint:
11328 llvm_unreachable("invalid cast kind for complex value");
11329
11330 case CK_LValueToRValue:
11331 case CK_AtomicToNonAtomic:
11332 case CK_NoOp:
11333 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11334
11335 case CK_Dependent:
11336 case CK_LValueBitCast:
11337 case CK_UserDefinedConversion:
11338 return Error(E);
11339
11340 case CK_FloatingRealToComplex: {
11341 APFloat &Real = Result.FloatReal;
11342 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
11343 return false;
11344
11345 Result.makeComplexFloat();
11346 Result.FloatImag = APFloat(Real.getSemantics());
11347 return true;
11348 }
11349
11350 case CK_FloatingComplexCast: {
11351 if (!Visit(E->getSubExpr()))
11352 return false;
11353
11354 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11355 QualType From
11356 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11357
11358 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
11359 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
11360 }
11361
11362 case CK_FloatingComplexToIntegralComplex: {
11363 if (!Visit(E->getSubExpr()))
11364 return false;
11365
11366 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11367 QualType From
11368 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11369 Result.makeComplexInt();
11370 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
11371 To, Result.IntReal) &&
11372 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
11373 To, Result.IntImag);
11374 }
11375
11376 case CK_IntegralRealToComplex: {
11377 APSInt &Real = Result.IntReal;
11378 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
11379 return false;
11380
11381 Result.makeComplexInt();
11382 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
11383 return true;
11384 }
11385
11386 case CK_IntegralComplexCast: {
11387 if (!Visit(E->getSubExpr()))
11388 return false;
11389
11390 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11391 QualType From
11392 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11393
11394 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
11395 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
11396 return true;
11397 }
11398
11399 case CK_IntegralComplexToFloatingComplex: {
11400 if (!Visit(E->getSubExpr()))
11401 return false;
11402
11403 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
11404 QualType From
11405 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
11406 Result.makeComplexFloat();
11407 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
11408 To, Result.FloatReal) &&
11409 HandleIntToFloatCast(Info, E, From, Result.IntImag,
11410 To, Result.FloatImag);
11411 }
11412 }
11413
11414 llvm_unreachable("unknown cast resulting in complex value");
11415}
11416
11417bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11418 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11419 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11420
11421 // Track whether the LHS or RHS is real at the type system level. When this is
11422 // the case we can simplify our evaluation strategy.
11423 bool LHSReal = false, RHSReal = false;
11424
11425 bool LHSOK;
11426 if (E->getLHS()->getType()->isRealFloatingType()) {
11427 LHSReal = true;
11428 APFloat &Real = Result.FloatReal;
11429 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
11430 if (LHSOK) {
11431 Result.makeComplexFloat();
11432 Result.FloatImag = APFloat(Real.getSemantics());
11433 }
11434 } else {
11435 LHSOK = Visit(E->getLHS());
11436 }
11437 if (!LHSOK && !Info.noteFailure())
11438 return false;
11439
11440 ComplexValue RHS;
11441 if (E->getRHS()->getType()->isRealFloatingType()) {
11442 RHSReal = true;
11443 APFloat &Real = RHS.FloatReal;
11444 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
11445 return false;
11446 RHS.makeComplexFloat();
11447 RHS.FloatImag = APFloat(Real.getSemantics());
11448 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
11449 return false;
11450
11451 assert(!(LHSReal && RHSReal) &&
11452 "Cannot have both operands of a complex operation be real.");
11453 switch (E->getOpcode()) {
11454 default: return Error(E);
11455 case BO_Add:
11456 if (Result.isComplexFloat()) {
11457 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
11458 APFloat::rmNearestTiesToEven);
11459 if (LHSReal)
11460 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11461 else if (!RHSReal)
11462 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
11463 APFloat::rmNearestTiesToEven);
11464 } else {
11465 Result.getComplexIntReal() += RHS.getComplexIntReal();
11466 Result.getComplexIntImag() += RHS.getComplexIntImag();
11467 }
11468 break;
11469 case BO_Sub:
11470 if (Result.isComplexFloat()) {
11471 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
11472 APFloat::rmNearestTiesToEven);
11473 if (LHSReal) {
11474 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11475 Result.getComplexFloatImag().changeSign();
11476 } else if (!RHSReal) {
11477 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
11478 APFloat::rmNearestTiesToEven);
11479 }
11480 } else {
11481 Result.getComplexIntReal() -= RHS.getComplexIntReal();
11482 Result.getComplexIntImag() -= RHS.getComplexIntImag();
11483 }
11484 break;
11485 case BO_Mul:
11486 if (Result.isComplexFloat()) {
11487 // This is an implementation of complex multiplication according to the
11488 // constraints laid out in C11 Annex G. The implementation uses the
11489 // following naming scheme:
11490 // (a + ib) * (c + id)
11491 ComplexValue LHS = Result;
11492 APFloat &A = LHS.getComplexFloatReal();
11493 APFloat &B = LHS.getComplexFloatImag();
11494 APFloat &C = RHS.getComplexFloatReal();
11495 APFloat &D = RHS.getComplexFloatImag();
11496 APFloat &ResR = Result.getComplexFloatReal();
11497 APFloat &ResI = Result.getComplexFloatImag();
11498 if (LHSReal) {
11499 assert(!RHSReal && "Cannot have two real operands for a complex op!");
11500 ResR = A * C;
11501 ResI = A * D;
11502 } else if (RHSReal) {
11503 ResR = C * A;
11504 ResI = C * B;
11505 } else {
11506 // In the fully general case, we need to handle NaNs and infinities
11507 // robustly.
11508 APFloat AC = A * C;
11509 APFloat BD = B * D;
11510 APFloat AD = A * D;
11511 APFloat BC = B * C;
11512 ResR = AC - BD;
11513 ResI = AD + BC;
11514 if (ResR.isNaN() && ResI.isNaN()) {
11515 bool Recalc = false;
11516 if (A.isInfinity() || B.isInfinity()) {
11517 A = APFloat::copySign(
11518 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11519 B = APFloat::copySign(
11520 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11521 if (C.isNaN())
11522 C = APFloat::copySign(APFloat(C.getSemantics()), C);
11523 if (D.isNaN())
11524 D = APFloat::copySign(APFloat(D.getSemantics()), D);
11525 Recalc = true;
11526 }
11527 if (C.isInfinity() || D.isInfinity()) {
11528 C = APFloat::copySign(
11529 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11530 D = APFloat::copySign(
11531 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11532 if (A.isNaN())
11533 A = APFloat::copySign(APFloat(A.getSemantics()), A);
11534 if (B.isNaN())
11535 B = APFloat::copySign(APFloat(B.getSemantics()), B);
11536 Recalc = true;
11537 }
11538 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
11539 AD.isInfinity() || BC.isInfinity())) {
11540 if (A.isNaN())
11541 A = APFloat::copySign(APFloat(A.getSemantics()), A);
11542 if (B.isNaN())
11543 B = APFloat::copySign(APFloat(B.getSemantics()), B);
11544 if (C.isNaN())
11545 C = APFloat::copySign(APFloat(C.getSemantics()), C);
11546 if (D.isNaN())
11547 D = APFloat::copySign(APFloat(D.getSemantics()), D);
11548 Recalc = true;
11549 }
11550 if (Recalc) {
11551 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
11552 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
11553 }
11554 }
11555 }
11556 } else {
11557 ComplexValue LHS = Result;
11558 Result.getComplexIntReal() =
11559 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
11560 LHS.getComplexIntImag() * RHS.getComplexIntImag());
11561 Result.getComplexIntImag() =
11562 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
11563 LHS.getComplexIntImag() * RHS.getComplexIntReal());
11564 }
11565 break;
11566 case BO_Div:
11567 if (Result.isComplexFloat()) {
11568 // This is an implementation of complex division according to the
11569 // constraints laid out in C11 Annex G. The implementation uses the
11570 // following naming scheme:
11571 // (a + ib) / (c + id)
11572 ComplexValue LHS = Result;
11573 APFloat &A = LHS.getComplexFloatReal();
11574 APFloat &B = LHS.getComplexFloatImag();
11575 APFloat &C = RHS.getComplexFloatReal();
11576 APFloat &D = RHS.getComplexFloatImag();
11577 APFloat &ResR = Result.getComplexFloatReal();
11578 APFloat &ResI = Result.getComplexFloatImag();
11579 if (RHSReal) {
11580 ResR = A / C;
11581 ResI = B / C;
11582 } else {
11583 if (LHSReal) {
11584 // No real optimizations we can do here, stub out with zero.
11585 B = APFloat::getZero(A.getSemantics());
11586 }
11587 int DenomLogB = 0;
11588 APFloat MaxCD = maxnum(abs(C), abs(D));
11589 if (MaxCD.isFinite()) {
11590 DenomLogB = ilogb(MaxCD);
11591 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
11592 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
11593 }
11594 APFloat Denom = C * C + D * D;
11595 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
11596 APFloat::rmNearestTiesToEven);
11597 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
11598 APFloat::rmNearestTiesToEven);
11599 if (ResR.isNaN() && ResI.isNaN()) {
11600 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
11601 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
11602 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
11603 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
11604 D.isFinite()) {
11605 A = APFloat::copySign(
11606 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11607 B = APFloat::copySign(
11608 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11609 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
11610 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
11611 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
11612 C = APFloat::copySign(
11613 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11614 D = APFloat::copySign(
11615 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11616 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
11617 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
11618 }
11619 }
11620 }
11621 } else {
11622 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
11623 return Error(E, diag::note_expr_divide_by_zero);
11624
11625 ComplexValue LHS = Result;
11626 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
11627 RHS.getComplexIntImag() * RHS.getComplexIntImag();
11628 Result.getComplexIntReal() =
11629 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
11630 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
11631 Result.getComplexIntImag() =
11632 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
11633 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
11634 }
11635 break;
11636 }
11637
11638 return true;
11639}
11640
11641bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11642 // Get the operand value into 'Result'.
11643 if (!Visit(E->getSubExpr()))
11644 return false;
11645
11646 switch (E->getOpcode()) {
11647 default:
11648 return Error(E);
11649 case UO_Extension:
11650 return true;
11651 case UO_Plus:
11652 // The result is always just the subexpr.
11653 return true;
11654 case UO_Minus:
11655 if (Result.isComplexFloat()) {
11656 Result.getComplexFloatReal().changeSign();
11657 Result.getComplexFloatImag().changeSign();
11658 }
11659 else {
11660 Result.getComplexIntReal() = -Result.getComplexIntReal();
11661 Result.getComplexIntImag() = -Result.getComplexIntImag();
11662 }
11663 return true;
11664 case UO_Not:
11665 if (Result.isComplexFloat())
11666 Result.getComplexFloatImag().changeSign();
11667 else
11668 Result.getComplexIntImag() = -Result.getComplexIntImag();
11669 return true;
11670 }
11671}
11672
11673bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11674 if (E->getNumInits() == 2) {
11675 if (E->getType()->isComplexType()) {
11676 Result.makeComplexFloat();
11677 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
11678 return false;
11679 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
11680 return false;
11681 } else {
11682 Result.makeComplexInt();
11683 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
11684 return false;
11685 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
11686 return false;
11687 }
11688 return true;
11689 }
11690 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
11691}
11692
11693//===----------------------------------------------------------------------===//
11694// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
11695// implicit conversion.
11696//===----------------------------------------------------------------------===//
11697
11698namespace {
11699class AtomicExprEvaluator :
11700 public ExprEvaluatorBase<AtomicExprEvaluator> {
11701 const LValue *This;
11702 APValue &Result;
11703public:
11704 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
11705 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
11706
11707 bool Success(const APValue &V, const Expr *E) {
11708 Result = V;
11709 return true;
11710 }
11711
11712 bool ZeroInitialization(const Expr *E) {
11713 ImplicitValueInitExpr VIE(
11714 E->getType()->castAs<AtomicType>()->getValueType());
11715 // For atomic-qualified class (and array) types in C++, initialize the
11716 // _Atomic-wrapped subobject directly, in-place.
11717 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
11718 : Evaluate(Result, Info, &VIE);
11719 }
11720
11721 bool VisitCastExpr(const CastExpr *E) {
11722 switch (E->getCastKind()) {
11723 default:
11724 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11725 case CK_NonAtomicToAtomic:
11726 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
11727 : Evaluate(Result, Info, E->getSubExpr());
11728 }
11729 }
11730};
11731} // end anonymous namespace
11732
11733static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
11734 EvalInfo &Info) {
11735 assert(E->isRValue() && E->getType()->isAtomicType());
11736 return AtomicExprEvaluator(Info, This, Result).Visit(E);
11737}
11738
11739//===----------------------------------------------------------------------===//
11740// Void expression evaluation, primarily for a cast to void on the LHS of a
11741// comma operator
11742//===----------------------------------------------------------------------===//
11743
11744namespace {
11745class VoidExprEvaluator
11746 : public ExprEvaluatorBase<VoidExprEvaluator> {
11747public:
11748 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
11749
11750 bool Success(const APValue &V, const Expr *e) { return true; }
11751
11752 bool ZeroInitialization(const Expr *E) { return true; }
11753
11754 bool VisitCastExpr(const CastExpr *E) {
11755 switch (E->getCastKind()) {
11756 default:
11757 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11758 case CK_ToVoid:
11759 VisitIgnoredValue(E->getSubExpr());
11760 return true;
11761 }
11762 }
11763
11764 bool VisitCallExpr(const CallExpr *E) {
11765 switch (E->getBuiltinCallee()) {
11766 default:
11767 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11768 case Builtin::BI__assume:
11769 case Builtin::BI__builtin_assume:
11770 // The argument is not evaluated!
11771 return true;
11772 }
11773 }
11774};
11775} // end anonymous namespace
11776
11777static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
11778 assert(E->isRValue() && E->getType()->isVoidType());
11779 return VoidExprEvaluator(Info).Visit(E);
11780}
11781
11782//===----------------------------------------------------------------------===//
11783// Top level Expr::EvaluateAsRValue method.
11784//===----------------------------------------------------------------------===//
11785
11786static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
11787 // In C, function designators are not lvalues, but we evaluate them as if they
11788 // are.
11789 QualType T = E->getType();
11790 if (E->isGLValue() || T->isFunctionType()) {
11791 LValue LV;
11792 if (!EvaluateLValue(E, LV, Info))
11793 return false;
11794 LV.moveInto(Result);
11795 } else if (T->isVectorType()) {
11796 if (!EvaluateVector(E, Result, Info))
11797 return false;
11798 } else if (T->isIntegralOrEnumerationType()) {
11799 if (!IntExprEvaluator(Info, Result).Visit(E))
11800 return false;
11801 } else if (T->hasPointerRepresentation()) {
11802 LValue LV;
11803 if (!EvaluatePointer(E, LV, Info))
11804 return false;
11805 LV.moveInto(Result);
11806 } else if (T->isRealFloatingType()) {
11807 llvm::APFloat F(0.0);
11808 if (!EvaluateFloat(E, F, Info))
11809 return false;
11810 Result = APValue(F);
11811 } else if (T->isAnyComplexType()) {
11812 ComplexValue C;
11813 if (!EvaluateComplex(E, C, Info))
11814 return false;
11815 C.moveInto(Result);
11816 } else if (T->isFixedPointType()) {
11817 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
11818 } else if (T->isMemberPointerType()) {
11819 MemberPtr P;
11820 if (!EvaluateMemberPointer(E, P, Info))
11821 return false;
11822 P.moveInto(Result);
11823 return true;
11824 } else if (T->isArrayType()) {
11825 LValue LV;
11826 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
11827 if (!EvaluateArray(E, LV, Value, Info))
11828 return false;
11829 Result = Value;
11830 } else if (T->isRecordType()) {
11831 LValue LV;
11832 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
11833 if (!EvaluateRecord(E, LV, Value, Info))
11834 return false;
11835 Result = Value;
11836 } else if (T->isVoidType()) {
11837 if (!Info.getLangOpts().CPlusPlus11)
11838 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
11839 << E->getType();
11840 if (!EvaluateVoid(E, Info))
11841 return false;
11842 } else if (T->isAtomicType()) {
11843 QualType Unqual = T.getAtomicUnqualifiedType();
11844 if (Unqual->isArrayType() || Unqual->isRecordType()) {
11845 LValue LV;
11846 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
11847 if (!EvaluateAtomic(E, &LV, Value, Info))
11848 return false;
11849 } else {
11850 if (!EvaluateAtomic(E, nullptr, Result, Info))
11851 return false;
11852 }
11853 } else if (Info.getLangOpts().CPlusPlus11) {
11854 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
11855 return false;
11856 } else {
11857 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11858 return false;
11859 }
11860
11861 return true;
11862}
11863
11864/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
11865/// cases, the in-place evaluation is essential, since later initializers for
11866/// an object can indirectly refer to subobjects which were initialized earlier.
11867static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
11868 const Expr *E, bool AllowNonLiteralTypes) {
11869 assert(!E->isValueDependent());
11870
11871 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
11872 return false;
11873
11874 if (E->isRValue()) {
11875 // Evaluate arrays and record types in-place, so that later initializers can
11876 // refer to earlier-initialized members of the object.
11877 QualType T = E->getType();
11878 if (T->isArrayType())
11879 return EvaluateArray(E, This, Result, Info);
11880 else if (T->isRecordType())
11881 return EvaluateRecord(E, This, Result, Info);
11882 else if (T->isAtomicType()) {
11883 QualType Unqual = T.getAtomicUnqualifiedType();
11884 if (Unqual->isArrayType() || Unqual->isRecordType())
11885 return EvaluateAtomic(E, &This, Result, Info);
11886 }
11887 }
11888
11889 // For any other type, in-place evaluation is unimportant.
11890 return Evaluate(Result, Info, E);
11891}
11892
11893/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
11894/// lvalue-to-rvalue cast if it is an lvalue.
11895static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
11896 if (E->getType().isNull())
11897 return false;
11898
11899 if (!CheckLiteralType(Info, E))
11900 return false;
11901
11902 if (!::Evaluate(Result, Info, E))
11903 return false;
11904
11905 if (E->isGLValue()) {
11906 LValue LV;
11907 LV.setFrom(Info.Ctx, Result);
11908 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
11909 return false;
11910 }
11911
11912 // Check this core constant expression is a constant expression.
11913 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
11914}
11915
11916static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
11917 const ASTContext &Ctx, bool &IsConst) {
11918 // Fast-path evaluations of integer literals, since we sometimes see files
11919 // containing vast quantities of these.
11920 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
11921 Result.Val = APValue(APSInt(L->getValue(),
11922 L->getType()->isUnsignedIntegerType()));
11923 IsConst = true;
11924 return true;
11925 }
11926
11927 // This case should be rare, but we need to check it before we check on
11928 // the type below.
11929 if (Exp->getType().isNull()) {
11930 IsConst = false;
11931 return true;
11932 }
11933
11934 // FIXME: Evaluating values of large array and record types can cause
11935 // performance problems. Only do so in C++11 for now.
11936 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
11937 Exp->getType()->isRecordType()) &&
11938 !Ctx.getLangOpts().CPlusPlus11) {
11939 IsConst = false;
11940 return true;
11941 }
11942 return false;
11943}
11944
11945static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
11946 Expr::SideEffectsKind SEK) {
11947 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
11948 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
11949}
11950
11951static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
11952 const ASTContext &Ctx, EvalInfo &Info) {
11953 bool IsConst;
11954 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
11955 return IsConst;
11956
11957 return EvaluateAsRValue(Info, E, Result.Val);
11958}
11959
11960static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
11961 const ASTContext &Ctx,
11962 Expr::SideEffectsKind AllowSideEffects,
11963 EvalInfo &Info) {
11964 if (!E->getType()->isIntegralOrEnumerationType())
11965 return false;
11966
11967 bool DidEvaluate = ::EvaluateAsRValue(E, ExprResult, Ctx, Info);
11968 if (!DidEvaluate || !ExprResult.Val.isInt() ||
11969 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) {
11970 // For intcap_t, pass through the result even if it isn't actually an
11971 // int.
11972 if (DidEvaluate &&
11973 E->getType()->isCHERICapabilityType(const_cast<ASTContext&>(Ctx)))
11974 if (ExprResult.Val.isLValue() &&
11975 ExprResult.Val.getLValueBase().isNull()) {
11976 // FIXME: Ugly hack!
11977 APSInt Val(64);
11978 Val = ExprResult.Val.getLValueOffset().getQuantity();
11979 ExprResult.Val = APValue(Val);
11980 return true;
11981 }
11982 return false;
11983 }
11984
11985 return true;
11986}
11987
11988static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
11989 const ASTContext &Ctx,
11990 Expr::SideEffectsKind AllowSideEffects,
11991 EvalInfo &Info) {
11992 if (!E->getType()->isFixedPointType())
11993 return false;
11994
11995 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
11996 return false;
11997
11998 if (!ExprResult.Val.isFixedPoint() ||
11999 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12000 return false;
12001
12002 return true;
12003}
12004
12005/// EvaluateAsRValue - Return true if this is a constant which we can fold using
12006/// any crazy technique (that has nothing to do with language standards) that
12007/// we want to. If this function returns true, it returns the folded constant
12008/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
12009/// will be applied to the result.
12010bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
12011 bool InConstantContext) const {
12012 assert(!isValueDependent() &&
12013 "Expression evaluator can't be called on a dependent expression.");
12014 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12015 Info.InConstantContext = InConstantContext;
12016 return ::EvaluateAsRValue(this, Result, Ctx, Info);
12017}
12018
12019bool Expr::EvaluateAsBooleanCondition(bool &Result,
12020 const ASTContext &Ctx) const {
12021 assert(!isValueDependent() &&
12022 "Expression evaluator can't be called on a dependent expression.");
12023 EvalResult Scratch;
12024 return EvaluateAsRValue(Scratch, Ctx) &&
12025 HandleConversionToBool(Scratch.Val, Result);
12026}
12027
12028bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
12029 SideEffectsKind AllowSideEffects) const {
12030 assert(!isValueDependent() &&
12031 "Expression evaluator can't be called on a dependent expression.");
12032 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12033 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
12034}
12035
12036bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
12037 SideEffectsKind AllowSideEffects) const {
12038 assert(!isValueDependent() &&
12039 "Expression evaluator can't be called on a dependent expression.");
12040 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12041 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
12042}
12043
12044bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
12045 SideEffectsKind AllowSideEffects) const {
12046 assert(!isValueDependent() &&
12047 "Expression evaluator can't be called on a dependent expression.");
12048
12049 if (!getType()->isRealFloatingType())
12050 return false;
12051
12052 EvalResult ExprResult;
12053 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
12054 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12055 return false;
12056
12057 Result = ExprResult.Val.getFloat();
12058 return true;
12059}
12060
12061bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
12062 assert(!isValueDependent() &&
12063 "Expression evaluator can't be called on a dependent expression.");
12064
12065 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
12066
12067 LValue LV;
12068 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
12069 !CheckLValueConstantExpression(Info, getExprLoc(),
12070 Ctx.getLValueReferenceType(getType()), LV,
12071 Expr::EvaluateForCodeGen))
12072 return false;
12073
12074 LV.moveInto(Result.Val);
12075 return true;
12076}
12077
12078bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
12079 const ASTContext &Ctx) const {
12080 assert(!isValueDependent() &&
12081 "Expression evaluator can't be called on a dependent expression.");
12082
12083 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
12084 EvalInfo Info(Ctx, Result, EM);
12085 Info.InConstantContext = true;
12086
12087 if (!::Evaluate(Result.Val, Info, this))
12088 return false;
12089
12090 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
12091 Usage);
12092}
12093
12094bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
12095 const VarDecl *VD,
12096 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
12097 assert(!isValueDependent() &&
12098 "Expression evaluator can't be called on a dependent expression.");
12099
12100 // FIXME: Evaluating initializers for large array and record types can cause
12101 // performance problems. Only do so in C++11 for now.
12102 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
12103 !Ctx.getLangOpts().CPlusPlus11)
12104 return false;
12105
12106 Expr::EvalStatus EStatus;
12107 EStatus.Diag = &Notes;
12108
12109 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
12110 ? EvalInfo::EM_ConstantExpression
12111 : EvalInfo::EM_ConstantFold);
12112 InitInfo.setEvaluatingDecl(VD, Value);
12113 InitInfo.InConstantContext = true;
12114
12115 LValue LVal;
12116 LVal.set(VD);
12117
12118 // C++11 [basic.start.init]p2:
12119 // Variables with static storage duration or thread storage duration shall be
12120 // zero-initialized before any other initialization takes place.
12121 // This behavior is not present in C.
12122 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
12123 !VD->getType()->isReferenceType()) {
12124 ImplicitValueInitExpr VIE(VD->getType());
12125 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
12126 /*AllowNonLiteralTypes=*/true))
12127 return false;
12128 }
12129
12130 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
12131 /*AllowNonLiteralTypes=*/true) ||
12132 EStatus.HasSideEffects)
12133 return false;
12134
12135 bool Result = CheckConstantExpression(InitInfo, VD->getLocation(),
12136 VD->getType(), Value);
12137 if (Result)
12138 GetIntCapLValue(Value, VD->getType(), const_cast<ASTContext&>(Ctx));
12139 return Result;
12140}
12141
12142/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
12143/// constant folded, but discard the result.
12144bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
12145 assert(!isValueDependent() &&
12146 "Expression evaluator can't be called on a dependent expression.");
12147
12148 EvalResult Result;
12149 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
12150 !hasUnacceptableSideEffect(Result, SEK);
12151}
12152
12153APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
12154 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
12155 assert(!isValueDependent() &&
12156 "Expression evaluator can't be called on a dependent expression.");
12157
12158 EvalResult EVResult;
12159 EVResult.Diag = Diag;
12160 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12161 Info.InConstantContext = true;
12162
12163 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
12164 (void)Result;
12165 assert(Result && "Could not evaluate expression");
12166 if (EVResult.Val.isLValue() && EVResult.Val.getLValueBase().isNull()) {
12167 // FIXME: Ugly hack!
12168 APSInt Val(64);
12169 Val = EVResult.Val.getLValueOffset().getQuantity();
12170 EVResult.Val = APValue(Val);
12171 }
12172 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
12173
12174 return EVResult.Val.getInt();
12175}
12176
12177APSInt Expr::EvaluateKnownConstIntCheckOverflow(
12178 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
12179 assert(!isValueDependent() &&
12180 "Expression evaluator can't be called on a dependent expression.");
12181
12182 EvalResult EVResult;
12183 EVResult.Diag = Diag;
12184 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
12185 Info.InConstantContext = true;
12186
12187 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
12188 (void)Result;
12189 assert(Result && "Could not evaluate expression");
12190 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
12191
12192 return EVResult.Val.getInt();
12193}
12194
12195void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
12196 assert(!isValueDependent() &&
12197 "Expression evaluator can't be called on a dependent expression.");
12198
12199 bool IsConst;
12200 EvalResult EVResult;
12201 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
12202 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
12203 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
12204 }
12205}
12206
12207bool Expr::EvalResult::isGlobalLValue() const {
12208 assert(Val.isLValue());
12209 return IsGlobalLValue(Val.getLValueBase());
12210}
12211
12212
12213/// isIntegerConstantExpr - this recursive routine will test if an expression is
12214/// an integer constant expression.
12215
12216/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
12217/// comma, etc
12218
12219// CheckICE - This function does the fundamental ICE checking: the returned
12220// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
12221// and a (possibly null) SourceLocation indicating the location of the problem.
12222//
12223// Note that to reduce code duplication, this helper does no evaluation
12224// itself; the caller checks whether the expression is evaluatable, and
12225// in the rare cases where CheckICE actually cares about the evaluated
12226// value, it calls into Evaluate.
12227
12228namespace {
12229
12230enum ICEKind {
12231 /// This expression is an ICE.
12232 IK_ICE,
12233 /// This expression is not an ICE, but if it isn't evaluated, it's
12234 /// a legal subexpression for an ICE. This return value is used to handle
12235 /// the comma operator in C99 mode, and non-constant subexpressions.
12236 IK_ICEIfUnevaluated,
12237 /// This expression is not an ICE, and is not a legal subexpression for one.
12238 IK_NotICE
12239};
12240
12241struct ICEDiag {
12242 ICEKind Kind;
12243 SourceLocation Loc;
12244
12245 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
12246};
12247
12248}
12249
12250static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
12251
12252static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
12253
12254static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
12255 Expr::EvalResult EVResult;
12256 Expr::EvalStatus Status;
12257 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
12258
12259 Info.InConstantContext = true;
12260 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
12261 !EVResult.Val.isInt())
12262 return ICEDiag(IK_NotICE, E->getBeginLoc());
12263
12264 return NoDiag();
12265}
12266
12267static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
12268 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
12269 if (!E->getType()->isIntegralOrEnumerationType())
12270 return ICEDiag(IK_NotICE, E->getBeginLoc());
12271
12272 switch (E->getStmtClass()) {
12273#define ABSTRACT_STMT(Node)
12274#define STMT(Node, Base) case Expr::Node##Class:
12275#define EXPR(Node, Base)
12276#include "clang/AST/StmtNodes.inc"
12277 case Expr::PredefinedExprClass:
12278 case Expr::FloatingLiteralClass:
12279 case Expr::ImaginaryLiteralClass:
12280 case Expr::StringLiteralClass:
12281 case Expr::ArraySubscriptExprClass:
12282 case Expr::OMPArraySectionExprClass:
12283 case Expr::MemberExprClass:
12284 case Expr::CompoundAssignOperatorClass:
12285 case Expr::CompoundLiteralExprClass:
12286 case Expr::ExtVectorElementExprClass:
12287 case Expr::DesignatedInitExprClass:
12288 case Expr::ArrayInitLoopExprClass:
12289 case Expr::ArrayInitIndexExprClass:
12290 case Expr::NoInitExprClass:
12291 case Expr::DesignatedInitUpdateExprClass:
12292 case Expr::ImplicitValueInitExprClass:
12293 case Expr::ParenListExprClass:
12294 case Expr::VAArgExprClass:
12295 case Expr::AddrLabelExprClass:
12296 case Expr::StmtExprClass:
12297 case Expr::CXXMemberCallExprClass:
12298 case Expr::CUDAKernelCallExprClass:
12299 case Expr::CXXDynamicCastExprClass:
12300 case Expr::CXXTypeidExprClass:
12301 case Expr::CXXUuidofExprClass:
12302 case Expr::MSPropertyRefExprClass:
12303 case Expr::MSPropertySubscriptExprClass:
12304 case Expr::CXXNullPtrLiteralExprClass:
12305 case Expr::UserDefinedLiteralClass:
12306 case Expr::CXXThisExprClass:
12307 case Expr::CXXThrowExprClass:
12308 case Expr::CXXNewExprClass:
12309 case Expr::CXXDeleteExprClass:
12310 case Expr::CXXPseudoDestructorExprClass:
12311 case Expr::UnresolvedLookupExprClass:
12312 case Expr::TypoExprClass:
12313 case Expr::DependentScopeDeclRefExprClass:
12314 case Expr::CXXConstructExprClass:
12315 case Expr::CXXInheritedCtorInitExprClass:
12316 case Expr::CXXStdInitializerListExprClass:
12317 case Expr::CXXBindTemporaryExprClass:
12318 case Expr::ExprWithCleanupsClass:
12319 case Expr::CXXTemporaryObjectExprClass:
12320 case Expr::CXXUnresolvedConstructExprClass:
12321 case Expr::CXXDependentScopeMemberExprClass:
12322 case Expr::UnresolvedMemberExprClass:
12323 case Expr::ObjCStringLiteralClass:
12324 case Expr::ObjCBoxedExprClass:
12325 case Expr::ObjCArrayLiteralClass:
12326 case Expr::ObjCDictionaryLiteralClass:
12327 case Expr::ObjCEncodeExprClass:
12328 case Expr::ObjCMessageExprClass:
12329 case Expr::ObjCSelectorExprClass:
12330 case Expr::ObjCProtocolExprClass:
12331 case Expr::ObjCIvarRefExprClass:
12332 case Expr::ObjCPropertyRefExprClass:
12333 case Expr::ObjCSubscriptRefExprClass:
12334 case Expr::ObjCIsaExprClass:
12335 case Expr::ObjCAvailabilityCheckExprClass:
12336 case Expr::ShuffleVectorExprClass:
12337 case Expr::ConvertVectorExprClass:
12338 case Expr::BlockExprClass:
12339 case Expr::NoStmtClass:
12340 case Expr::OpaqueValueExprClass:
12341 case Expr::PackExpansionExprClass:
12342 case Expr::SubstNonTypeTemplateParmPackExprClass:
12343 case Expr::FunctionParmPackExprClass:
12344 case Expr::AsTypeExprClass:
12345 case Expr::ObjCIndirectCopyRestoreExprClass:
12346 case Expr::MaterializeTemporaryExprClass:
12347 case Expr::PseudoObjectExprClass:
12348 case Expr::AtomicExprClass:
12349 case Expr::LambdaExprClass:
12350 case Expr::CXXFoldExprClass:
12351 case Expr::CoawaitExprClass:
12352 case Expr::DependentCoawaitExprClass:
12353 case Expr::CoyieldExprClass:
12354 return ICEDiag(IK_NotICE, E->getBeginLoc());
12355
12356 case Expr::InitListExprClass: {
12357 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
12358 // form "T x = { a };" is equivalent to "T x = a;".
12359 // Unless we're initializing a reference, T is a scalar as it is known to be
12360 // of integral or enumeration type.
12361 if (E->isRValue())
12362 if (cast<InitListExpr>(E)->getNumInits() == 1)
12363 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
12364 return ICEDiag(IK_NotICE, E->getBeginLoc());
12365 }
12366
12367 case Expr::SizeOfPackExprClass:
12368 case Expr::GNUNullExprClass:
12369 case Expr::SourceLocExprClass:
12370 return NoDiag();
12371
12372 case Expr::SubstNonTypeTemplateParmExprClass:
12373 return
12374 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
12375
12376 case Expr::ConstantExprClass:
12377 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
12378
12379 case Expr::ParenExprClass:
12380 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
12381 case Expr::GenericSelectionExprClass:
12382 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
12383 case Expr::IntegerLiteralClass:
12384 case Expr::FixedPointLiteralClass:
12385 case Expr::CharacterLiteralClass:
12386 case Expr::ObjCBoolLiteralExprClass:
12387 case Expr::CXXBoolLiteralExprClass:
12388 case Expr::CXXScalarValueInitExprClass:
12389 case Expr::TypeTraitExprClass:
12390 case Expr::ArrayTypeTraitExprClass:
12391 case Expr::ExpressionTraitExprClass:
12392 case Expr::CXXNoexceptExprClass:
12393 return NoDiag();
12394 case Expr::CallExprClass:
12395 case Expr::CXXOperatorCallExprClass: {
12396 // C99 6.6/3 allows function calls within unevaluated subexpressions of
12397 // constant expressions, but they can never be ICEs because an ICE cannot
12398 // contain an operand of (pointer to) function type.
12399 const CallExpr *CE = cast<CallExpr>(E);
12400 if (CE->getBuiltinCallee())
12401 return CheckEvalInICE(E, Ctx);
12402 return ICEDiag(IK_NotICE, E->getBeginLoc());
12403 }
12404 case Expr::DeclRefExprClass: {
12405 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
12406 return NoDiag();
12407 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
12408 if (Ctx.getLangOpts().CPlusPlus &&
12409 D && IsConstNonVolatile(D->getType())) {
12410 // Parameter variables are never constants. Without this check,
12411 // getAnyInitializer() can find a default argument, which leads
12412 // to chaos.
12413 if (isa<ParmVarDecl>(D))
12414 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12415
12416 // C++ 7.1.5.1p2
12417 // A variable of non-volatile const-qualified integral or enumeration
12418 // type initialized by an ICE can be used in ICEs.
12419 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
12420 if (!Dcl->getType()->isIntegralOrEnumerationType())
12421 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12422
12423 const VarDecl *VD;
12424 // Look for a declaration of this variable that has an initializer, and
12425 // check whether it is an ICE.
12426 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
12427 return NoDiag();
12428 else
12429 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12430 }
12431 }
12432 return ICEDiag(IK_NotICE, E->getBeginLoc());
12433 }
12434 case Expr::UnaryOperatorClass: {
12435 const UnaryOperator *Exp = cast<UnaryOperator>(E);
12436 switch (Exp->getOpcode()) {
12437 case UO_PostInc:
12438 case UO_PostDec:
12439 case UO_PreInc:
12440 case UO_PreDec:
12441 case UO_AddrOf:
12442 case UO_Deref:
12443 case UO_Coawait:
12444 // C99 6.6/3 allows increment and decrement within unevaluated
12445 // subexpressions of constant expressions, but they can never be ICEs
12446 // because an ICE cannot contain an lvalue operand.
12447 return ICEDiag(IK_NotICE, E->getBeginLoc());
12448 case UO_Extension:
12449 case UO_LNot:
12450 case UO_Plus:
12451 case UO_Minus:
12452 case UO_Not:
12453 case UO_Real:
12454 case UO_Imag:
12455 return CheckICE(Exp->getSubExpr(), Ctx);
12456 }
12457 llvm_unreachable("invalid unary operator class");
12458 }
12459 case Expr::OffsetOfExprClass: {
12460 // Note that per C99, offsetof must be an ICE. And AFAIK, using
12461 // EvaluateAsRValue matches the proposed gcc behavior for cases like
12462 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
12463 // compliance: we should warn earlier for offsetof expressions with
12464 // array subscripts that aren't ICEs, and if the array subscripts
12465 // are ICEs, the value of the offsetof must be an integer constant.
12466 return CheckEvalInICE(E, Ctx);
12467 }
12468 case Expr::UnaryExprOrTypeTraitExprClass: {
12469 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
12470 if ((Exp->getKind() == UETT_SizeOf) &&
12471 Exp->getTypeOfArgument()->isVariableArrayType())
12472 return ICEDiag(IK_NotICE, E->getBeginLoc());
12473 return NoDiag();
12474 }
12475 case Expr::BinaryOperatorClass: {
12476 const BinaryOperator *Exp = cast<BinaryOperator>(E);
12477 switch (Exp->getOpcode()) {
12478 case BO_PtrMemD:
12479 case BO_PtrMemI:
12480 case BO_Assign:
12481 case BO_MulAssign:
12482 case BO_DivAssign:
12483 case BO_RemAssign:
12484 case BO_AddAssign:
12485 case BO_SubAssign:
12486 case BO_ShlAssign:
12487 case BO_ShrAssign:
12488 case BO_AndAssign:
12489 case BO_XorAssign:
12490 case BO_OrAssign:
12491 // C99 6.6/3 allows assignments within unevaluated subexpressions of
12492 // constant expressions, but they can never be ICEs because an ICE cannot
12493 // contain an lvalue operand.
12494 return ICEDiag(IK_NotICE, E->getBeginLoc());
12495
12496 case BO_Mul:
12497 case BO_Div:
12498 case BO_Rem:
12499 case BO_Add:
12500 case BO_Sub:
12501 case BO_Shl:
12502 case BO_Shr:
12503 case BO_LT:
12504 case BO_GT:
12505 case BO_LE:
12506 case BO_GE:
12507 case BO_EQ:
12508 case BO_NE:
12509 case BO_And:
12510 case BO_Xor:
12511 case BO_Or:
12512 case BO_Comma:
12513 case BO_Cmp: {
12514 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12515 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
12516 if (Exp->getOpcode() == BO_Div ||
12517 Exp->getOpcode() == BO_Rem) {
12518 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
12519 // we don't evaluate one.
12520 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
12521 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
12522 if (REval == 0)
12523 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12524 if (REval.isSigned() && REval.isAllOnesValue()) {
12525 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
12526 if (LEval.isMinSignedValue())
12527 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12528 }
12529 }
12530 }
12531 if (Exp->getOpcode() == BO_Comma) {
12532 if (Ctx.getLangOpts().C99) {
12533 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
12534 // if it isn't evaluated.
12535 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
12536 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12537 } else {
12538 // In both C89 and C++, commas in ICEs are illegal.
12539 return ICEDiag(IK_NotICE, E->getBeginLoc());
12540 }
12541 }
12542 return Worst(LHSResult, RHSResult);
12543 }
12544 case BO_LAnd:
12545 case BO_LOr: {
12546 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12547 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
12548 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
12549 // Rare case where the RHS has a comma "side-effect"; we need
12550 // to actually check the condition to see whether the side
12551 // with the comma is evaluated.
12552 if ((Exp->getOpcode() == BO_LAnd) !=
12553 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
12554 return RHSResult;
12555 return NoDiag();
12556 }
12557
12558 return Worst(LHSResult, RHSResult);
12559 }
12560 }
12561 llvm_unreachable("invalid binary operator kind");
12562 }
12563 case Expr::ImplicitCastExprClass:
12564 case Expr::CStyleCastExprClass:
12565 case Expr::CXXFunctionalCastExprClass:
12566 case Expr::CXXStaticCastExprClass:
12567 case Expr::CXXReinterpretCastExprClass:
12568 case Expr::CXXConstCastExprClass:
12569 case Expr::ObjCBridgedCastExprClass: {
12570 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
12571 if (isa<ExplicitCastExpr>(E)) {
12572 if (const FloatingLiteral *FL
12573 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
12574 unsigned DestWidth = Ctx.getIntRange(E->getType());
12575 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
12576 APSInt IgnoredVal(DestWidth, !DestSigned);
12577 bool Ignored;
12578 // If the value does not fit in the destination type, the behavior is
12579 // undefined, so we are not required to treat it as a constant
12580 // expression.
12581 if (FL->getValue().convertToInteger(IgnoredVal,
12582 llvm::APFloat::rmTowardZero,
12583 &Ignored) & APFloat::opInvalidOp)
12584 return ICEDiag(IK_NotICE, E->getBeginLoc());
12585 return NoDiag();
12586 }
12587 }
12588 switch (cast<CastExpr>(E)->getCastKind()) {
12589 case CK_LValueToRValue:
12590 case CK_AtomicToNonAtomic:
12591 case CK_NonAtomicToAtomic:
12592 case CK_NoOp:
12593 case CK_IntegralToBoolean:
12594 case CK_IntegralCast:
12595 return CheckICE(SubExpr, Ctx);
12596 default:
12597 return ICEDiag(IK_NotICE, E->getBeginLoc());
12598 }
12599 }
12600 case Expr::BinaryConditionalOperatorClass: {
12601 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
12602 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
12603 if (CommonResult.Kind == IK_NotICE) return CommonResult;
12604 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
12605 if (FalseResult.Kind == IK_NotICE) return FalseResult;
12606 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
12607 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
12608 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
12609 return FalseResult;
12610 }
12611 case Expr::ConditionalOperatorClass: {
12612 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
12613 // If the condition (ignoring parens) is a __builtin_constant_p call,
12614 // then only the true side is actually considered in an integer constant
12615 // expression, and it is fully evaluated. This is an important GNU
12616 // extension. See GCC PR38377 for discussion.
12617 if (const CallExpr *CallCE
12618 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
12619 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
12620 return CheckEvalInICE(E, Ctx);
12621 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
12622 if (CondResult.Kind == IK_NotICE)
12623 return CondResult;
12624
12625 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
12626 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
12627
12628 if (TrueResult.Kind == IK_NotICE)
12629 return TrueResult;
12630 if (FalseResult.Kind == IK_NotICE)
12631 return FalseResult;
12632 if (CondResult.Kind == IK_ICEIfUnevaluated)
12633 return CondResult;
12634 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
12635 return NoDiag();
12636 // Rare case where the diagnostics depend on which side is evaluated
12637 // Note that if we get here, CondResult is 0, and at least one of
12638 // TrueResult and FalseResult is non-zero.
12639 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
12640 return FalseResult;
12641 return TrueResult;
12642 }
12643 case Expr::CXXDefaultArgExprClass:
12644 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
12645 case Expr::CXXDefaultInitExprClass:
12646 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
12647 case Expr::ChooseExprClass: {
12648 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
12649 }
12650 }
12651
12652 llvm_unreachable("Invalid StmtClass!");
12653}
12654
12655/// Evaluate an expression as a C++11 integral constant expression.
12656static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
12657 const Expr *E,
12658 llvm::APSInt *Value,
12659 SourceLocation *Loc) {
12660 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12661 if (Loc) *Loc = E->getExprLoc();
12662 return false;
12663 }
12664
12665 APValue Result;
12666 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
12667 return false;
12668
12669 if (!Result.isInt()) {
12670 if (Loc) *Loc = E->getExprLoc();
12671 return false;
12672 }
12673
12674 if (Value) *Value = Result.getInt();
12675 return true;
12676}
12677
12678bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
12679 SourceLocation *Loc) const {
12680 assert(!isValueDependent() &&
12681 "Expression evaluator can't be called on a dependent expression.");
12682
12683 if (Ctx.getLangOpts().CPlusPlus11)
12684 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
12685
12686 ICEDiag D = CheckICE(this, Ctx);
12687 if (D.Kind != IK_ICE) {
12688 if (Loc) *Loc = D.Loc;
12689 return false;
12690 }
12691 return true;
12692}
12693
12694bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
12695 SourceLocation *Loc, bool isEvaluated) const {
12696 assert(!isValueDependent() &&
12697 "Expression evaluator can't be called on a dependent expression.");
12698
12699 if (Ctx.getLangOpts().CPlusPlus11)
12700 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
12701
12702 if (!isIntegerConstantExpr(Ctx, Loc))
12703 return false;
12704
12705 // The only possible side-effects here are due to UB discovered in the
12706 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
12707 // required to treat the expression as an ICE, so we produce the folded
12708 // value.
12709 EvalResult ExprResult;
12710 Expr::EvalStatus Status;
12711 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
12712 Info.InConstantContext = true;
12713
12714 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
12715 llvm_unreachable("ICE cannot be evaluated!");
12716
12717 Value = ExprResult.Val.getInt();
12718 return true;
12719}
12720
12721bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
12722 assert(!isValueDependent() &&
12723 "Expression evaluator can't be called on a dependent expression.");
12724
12725 return CheckICE(this, Ctx).Kind == IK_ICE;
12726}
12727
12728bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
12729 SourceLocation *Loc) const {
12730 assert(!isValueDependent() &&
12731 "Expression evaluator can't be called on a dependent expression.");
12732
12733 // We support this checking in C++98 mode in order to diagnose compatibility
12734 // issues.
12735 assert(Ctx.getLangOpts().CPlusPlus);
12736
12737 // Build evaluation settings.
12738 Expr::EvalStatus Status;
12739 SmallVector<PartialDiagnosticAt, 8> Diags;
12740 Status.Diag = &Diags;
12741 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
12742
12743 APValue Scratch;
12744 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
12745
12746 if (!Diags.empty()) {
12747 IsConstExpr = false;
12748 if (Loc) *Loc = Diags[0].first;
12749 } else if (!IsConstExpr) {
12750 // FIXME: This shouldn't happen.
12751 if (Loc) *Loc = getExprLoc();
12752 }
12753
12754 return IsConstExpr;
12755}
12756
12757bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
12758 const FunctionDecl *Callee,
12759 ArrayRef<const Expr*> Args,
12760 const Expr *This) const {
12761 assert(!isValueDependent() &&
12762 "Expression evaluator can't be called on a dependent expression.");
12763
12764 Expr::EvalStatus Status;
12765 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
12766 Info.InConstantContext = true;
12767
12768 LValue ThisVal;
12769 const LValue *ThisPtr = nullptr;
12770 if (This) {
12771#ifndef NDEBUG
12772 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
12773 assert(MD && "Don't provide `this` for non-methods.");
12774 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
12775#endif
12776 if (EvaluateObjectArgument(Info, This, ThisVal))
12777 ThisPtr = &ThisVal;
12778 if (Info.EvalStatus.HasSideEffects)
12779 return false;
12780 }
12781
12782 ArgVector ArgValues(Args.size());
12783 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
12784 I != E; ++I) {
12785 if ((*I)->isValueDependent() ||
12786 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
12787 // If evaluation fails, throw away the argument entirely.
12788 ArgValues[I - Args.begin()] = APValue();
12789 if (Info.EvalStatus.HasSideEffects)
12790 return false;
12791 }
12792
12793 // Build fake call to Callee.
12794 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
12795 ArgValues.data());
12796 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
12797}
12798
12799bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
12800 SmallVectorImpl<
12801 PartialDiagnosticAt> &Diags) {
12802 // FIXME: It would be useful to check constexpr function templates, but at the
12803 // moment the constant expression evaluator cannot cope with the non-rigorous
12804 // ASTs which we build for dependent expressions.
12805 if (FD->isDependentContext())
12806 return true;
12807
12808 Expr::EvalStatus Status;
12809 Status.Diag = &Diags;
12810
12811 EvalInfo Info(FD->getASTContext(), Status,
12812 EvalInfo::EM_PotentialConstantExpression);
12813 Info.InConstantContext = true;
12814
12815 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
12816 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
12817
12818 // Fabricate an arbitrary expression on the stack and pretend that it
12819 // is a temporary being used as the 'this' pointer.
12820 LValue This;
12821 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
12822 This.set({&VIE, Info.CurrentCall->Index});
12823
12824 ArrayRef<const Expr*> Args;
12825
12826 APValue Scratch;
12827 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
12828 // Evaluate the call as a constant initializer, to allow the construction
12829 // of objects of non-literal types.
12830 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
12831 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
12832 } else {
12833 SourceLocation Loc = FD->getLocation();
12834 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
12835 Args, FD->getBody(), Info, Scratch, nullptr);
12836 }
12837
12838 return Diags.empty();
12839}
12840
12841bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
12842 const FunctionDecl *FD,
12843 SmallVectorImpl<
12844 PartialDiagnosticAt> &Diags) {
12845 assert(!E->isValueDependent() &&
12846 "Expression evaluator can't be called on a dependent expression.");
12847
12848 Expr::EvalStatus Status;
12849 Status.Diag = &Diags;
12850
12851 EvalInfo Info(FD->getASTContext(), Status,
12852 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
12853 Info.InConstantContext = true;
12854
12855 // Fabricate a call stack frame to give the arguments a plausible cover story.
12856 ArrayRef<const Expr*> Args;
12857 ArgVector ArgValues(0);
12858 bool Success = EvaluateArgs(Args, ArgValues, Info);
12859 (void)Success;
12860 assert(Success &&
12861 "Failed to set up arguments for potential constant evaluation");
12862 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
12863
12864 APValue ResultScratch;
12865 Evaluate(ResultScratch, Info, E);
12866 return Diags.empty();
12867}
12868
12869bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
12870 unsigned Type) const {
12871 if (!getType()->isPointerType())
12872 return false;
12873
12874 Expr::EvalStatus Status;
12875 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
12876 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
12877}
12878